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" }
];
1
2
3
4
5
6
7
8
9
⬇️
//结果
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" }]}
]
1
2
3
4
5
6
?具体操作
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);