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;
		  }, []);
		}

你可能感兴趣的:(javascript,前端,es6)