【前端能看懂的代码】之经典去重

386 阅读2分钟

古都近日阴雨多,早晚需要穿秋裤。吾却孤注要风度,身体发抖无人助。

在写代码的过程中,我们经常会遇到需要去重对象、数组等组装数据,这些都是ES6的一些基本功,对于特别想要代码优雅的开发来说尤为重要。为了方便你我还有那个她,我们一些来看看吧!

明确需求是什么?

去掉数组里面不想要的对象!!!

我们需要哪些知识点?

  • Object.entries遍历对象为二维数组
  • 利用reduce来‘累计’我们想要呈现的数据
  • includes过滤不需要要的id

开始看代码

1. 找到value为false的id,构造成数组;

const a = {1:false,2:true,3:false}
const result = Object.entries(a).reduce(
        (result, [key, value]) => {
          if (!value) {
            result.push(key)
          }
          return result
        },
        []
      )
 console.log(result)

2. 过滤掉数组中指定id的对象;

const b = [{id:1,name:'zx'},{id:2,name:'cv'},{id:3,name:'yh'}]
const newSelected = b.filter(item => {
        return !result.join(',').includes(item.id)
      })
 console.log(newSelected)
 

这样,我们就去掉了不想要的对象数组了;

3.数组对象如何去重

const array = [{id:1},{id:2},{id:1}]
const temp = {}
const obj = array.reduce((total,next) =>{
  temp[next.id]? '' : temp[next.id] = true && total.push(next)
  return total
},[])
console.log(obj)

let arr = [{id: 1,name: 'aa'}, {id: 2,name: '66'}, {id: 2,name: '99999'}]
const obj = []
const filterObj = (arr, key) => {
    arr.reduce((prev,next)=> {
      if(!prev.includes(next[key])){
      prev.push(next[key])
      obj.push(next)
      }
      return prev
    },[])
}
filterObj(arr,'id')
console.log(obj)

4.地址参数解析

a: reduce使用
function qs(search) {
  if (typeof search !== 'string' || !search) return search
  return search.split('&').reduce((res, cur) => {
    const arr = cur.split('=')
    return Object.assign({ [arr[0]]: arr[1] }, res)
  }, {})
}
const b = qs('a=1&b=2')
console.log(b)
b:使用URLSearchParam api
const a = new URL('https://s.taobao.com/search?name=list&age=23')
const b = new URLSearchParams(a.search)
const obj={
  name: b.get('name'),
  age: b.get('age')
}
console.log(obj)

5.转换成树形数据

const a = [ { id: 1, pid: 0 }, { id: 2, pid: 0 },{ id: 3, pid: 1 },{ id: 4, pid: 1 }, { id: 5, pid: 2 }, { id: 6, pid: 2 }]

function ArrayToTree(list) {
    const map = new Map()
    list.forEach(item => {
        if (!map.has(item.pid)) {
            map.set(item.pid, [])
        }
        map.get(item.pid).push(item)
    })
    function recursive(pid) {
        return  map.get(pid).map(item => {
            if (map.has(item.id)) {
                item.children = recursive(item.id)
            }
            return item
        })
    }
    return recursive(0)
}
const a = [ { id: 1, pid: 0 }, { id: 2, pid: 0 },{ id: 3, pid: 1 },{ id: 4, pid: 1 }, { id: 5, pid: 2 }, { id: 6, pid: 2 }]
const data = ArrayToTree(a)
console.log(...data)

6. 判断两个对象是否相等

let obj1 = { id: 1, name: '张三' }
let obj2 = { id: 1, name: '张三' }

function isEqual(a, b) {
  // getOwnPropertyNames
  const aProps = Object.keys(a)
  const bProps = Object.keys(b)
  if (aProps.length !== bProps.length) {
    return false
  }
  for (let i = 0; i < aProps.length; i++) {
    let propName = aProps[i]
    let propA = a[propName]
    let propB = b[propName]
    if (propA !== propB) {
      return false
    }
  }
  return true
}

isEqual(obj1, obj2)

7: 拉平数组

const a = [1, 2, [3, [4]]]

function flatten(arr) {
  return arr.reduce((total, current) => {
    return total.concat(Array.isArray(current) ? flatten(current) : current)
  }, [])
}

console.log(flatten(a))

结束语

真正的英雄不是改变世界,而是改变自己生活的每一天~