将数组对象中某个值相同的对象合并成一个新对象

  • Post author:
  • Post category:其他


js将数组对象中某个值相同的对象合并成一个新对象

需求:beforeData – – > afterData

//源数组

var beforeData= [

{ name: “tony”, id: “1”, age: “20” },

{ name: “jack”, id: “2”, age: “21” },

{ name: “tony”, id: “3”, age: “50” },

{ name: “jack”, id: “4”, age: “10” },

{ name: “mark”, id: “5”, age: “22” },

{ name: “mark”, id: “6”, age: “40” }

];

//结果

afterData= [

{name: “tony”,origin: [{ name: “tony”, id: “1”, age: “20” },{ name: “tony”, id: “3”, age: “50” }]},

{name: “jack”,origin: [{ name: “jack”, id: “2”, age: “21” },{ name: “jack”, id: “4”, age: “10” }]},

{name: “mark”,origin: [{ name: “mark”, id: “5”, age: “22” },{ name: “mark”, id: “6”, age: “40” }]}

]


具体操作

let tempArr = [];
    for (let i = 0; i < beforeData.length; i++) {
        if (tempArr.indexOf(beforeData[i].name) === -1) {
            this.afterData.push({
                name: beforeData[i].name,
                origin: [beforeData[i]]
            });
            tempArr.push(beforeData[i].name);
        } else {
            for (let j = 0; j < this.afterData.length; j++) {
                if (this.afterData[j].name == beforeData[i].name) {
                    this.afterData[j].origin.push(beforeData[i]);
                    break;
                }
            }
        }
    }
console.log(this.afterData,888);



版权声明:本文为weixin_42459543原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。