js数组对象去重并合并

        //原数组
        let array=[
            {menuId:1,name:"小一"},
            {menuId:1,name:"小二"},
            {menuId:1,name:"小三"},
            {menuId:2,name:"小四"},
            {menuId:2,name:"小五"},
            {menuId:2,name:"小六"},
        ]
        //格式化后
        let newArray=[
            // {menuId:1,name:["小一","小二","小三"]},
            // {menuId:2,name:["小四","小五","小六"]},
        ]
        //方法一:
        let map={}
        array.forEach(item=>{
            if(!map[item.menuId]){
                map[item.menuId]=[]
            }
            map[item.menuId].push(item.name)
        })
        //Object.entries方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组
        let arr2=Object.entries(map).map(item=>{
            return {
                menuId:item[0],
                name:item[1]
            }
        })
        console.log(arr2);// [{menuId:1,name:["小一","小二","小三"]},{menuId:2,name:["小四","小五","小六"]}]


// js 对象数组去重并且保留最后的对象


        // 去重
        var arr = [
            { name: '张三', id: 1, integral: 10 },
            { name: '李四', id: 2, integral: 20 },
            { name: '王五', id: 3, integral: 30 },
            { name: '赵六', id: 4, integral: 40 },
            { name: '王五', id: 3, integral: 10 },
            { name: '王五', id: 3, integral: 80 },
            { name: '赵六', id: 4, integral: 20 },
        ]
        console.log(arrayUnique2(arr, 'id'), 'name')
 
        /*
        reducer 函数接收4个参数:
            Accumulator (acc) (累计器)
            Current Value (cur) (当前值)
            Current Index (index) (当前索引)
            Source Array (srcArray) (源数组)
        */
		function arrayUnique2(arr, name) {
		  var hash = {};
		  return arr.reduce(function (acc, cru,index) {
		      if (!hash[cru[name]]) {
		          hash[cru[name]] = {index:index}
		          acc.push(cru)
		      }else{
		          acc.splice(hash[cru[name]]['index'],1,cru)
		      }
		      return acc;
		  }, []);
		}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值