根据数组中某个对象的属性对该数组去重

在项目过程中,有时候就需要对接收到的数据做去重处理:

1.如果是单纯的只有一层数据结构的数据,去重的话我一般会用ES6的 new Set 方法:

let arr = [1,4,5,7,3,6,1,4];

let newArr = Array.from(new Set(arr));

console.log(newArr);

//[1,4,5,7,3,6]

2.但是真正在项目中,我们很少能遇到上面的这种数组,所以当遇到数组中包含对象的时候,我一般用以下的方法去重:

methods:{
handleDuplicateRemoval(list){
          let userList = [];
          let hash = {};
          userList = list.reduce((preVal, curVal) => {
            hash[curVal.name] ? '' : hash[curVal.name] = true && preVal.push(curVal);
            return preVal
          }, []);
          return userList;
        },

getListData(){
    let list = [
            {
             id:1,
             name:'张三',
             companyId:666
             },
            {
             id:2,
             name:'李四',
             companyId:222
             },
            {
             id:3,
             name:'张三',
             companyId:888
             }
         ];
}
  
let listData = this.handleDuplicateRemoval(list);

//listData为根据name去重之后新的数组
}


猜你喜欢

转载自blog.csdn.net/qq_41550865/article/details/105126548