数组中的对象去重及重复id的数据重构

本文介绍了一种利用JavaScript中的Array.prototype.reduce方法对数组中的对象进行去重的技术。通过两个实例展示了如何根据对象的id属性去除重复项,以及如何处理需要合并相同id下不同text的情况。

往常在对数组中的对象去重如:

 let  person = [
   { id : 1,text:1},
   { id : 2,text:2},
   { id : 3,text:3},
   { id : 1,text:4}   
]

要想将 id  重叠的 数据去重,我们通常会采用复杂的对数组循环判断的方式,但是在ES5出现reduce之后,我们可以采用reduce来对数组中的对象去重。

在 Array.prototype.reduce 方法中,可以传递四个参数:

previousValue : 初始值或上一次 回调函数的返回值;

currentValue : 本次循环(回调)将要执行的值;

index : "currentValue " 的索引值;

arr  : 数组本身

 

在使用reduce对数组去重一般只需要用到  previousValue  和 currentValue ;

 

实现过程如下:

  let  person = [
    { id:1 , text: 3},
    { id:2 , text: 4},
    { id:5 , text: 3},
    { id:1 , text: 2}  
  ];
    
  let obj = {};

  person = person.reduce( ( pre,cur ) => {
     obj[cur.id] ? "" : obj[cur.id] = true && pre.push(cur);
     return pre;
  },[]);

  console.log(person);

输出结果如下:

当然,也有可能需求是将 id 相同的部分的 text 组合成一个数组,实现过程如下:

let  person = [
        { id:1 , text: 3},
        { id:2 , text: 4},
        { id:5 , text: 3},
        { id:1 , text: 2},
        { id:2 , text: 5},
        { id:2 , text: 6}
    ];

    let obj = {};
    
    person = person.reduce( ( pre,cur ) => {
                if(obj[cur.id]){
                   pre.map(
                      item => item.id === cur.id ? item.text = Array.prototype.concat(item.text,cur.text): ''
                   );
                }else {
                   obj[cur.id] = true &&  pre.push(cur);
                }    
            return pre;
    },[]);

  console.log(person);        

输出结果如下:

 

如果对大家有用记得来github  点 star ,https://github.com/pppa1238yu 感激不尽~~!!!!!

转载于:https://www.cnblogs.com/guoxianjunweb/p/8629644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值