js中根据数组对象中的相同id值进⾏合并,并将name值合并,并且⽤逗号隔开返回新的数组对象
1.模拟⼀个假的数组
let dataArr = [
{
id:1,
name:"A",
score:10,
},
{
id:2,
name:"B",
score:10,
},
{
id:1,
name:"c",
score:10,
},
{
id:2,
name:"D",
score:10,
},
]
2.合并对象数组
var beforeData = dataArr;      //将dataArr赋值给beforeData  也可直接操作dataArr
let tempArr = [];
let afterData = [];//新数组
for (let i = 0; i < beforeData.length; i++) {
if (tempArr.indexOf(beforeData[i].id) === -1) {
afterData.push({
id: beforeData[i].id,
js合并两个数组score: beforeData[i].score,
name: [beforeData[i].name],
});
tempArr.push(beforeData[i].id);
} else {
for (let j = 0; j < afterData.length; j++) {
if (afterData[j].id == beforeData[i].id) {
afterData[j].name.push(beforeData[i].name);
break;
}
}
}
}
//循环afterData并且合并name值⽤逗号隔开
afterData.map((item) => {
item.name= item.name.join(",");
});
console.log(afterData,'afterData')
3.返回新的数组对象
[{
id:1,
name:"A,C",  score:10,  },
{
id:2,
name:"B,D",  score:10,  },]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。