js将数组对象中某个值相同的对象合并成⼀个新对象不知道⼤家在开发过程中有没有遇到这样的数据转换:
数据源是这样的
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" }
]
要将数据中name相同的项合并成⼀个对象(如下):
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 < this.beforeData.length; i++) {
if (tempArr.indexOf(this.beforeData[i].name) === -1) {
this.afterData.push({
name: this.beforeData[i].name,
origin: [this.beforeData[i]]
js合并两个数组
});
tempArr.push(this.beforeData[i].name);
} else {
for (let j = 0; j < this.afterData.length; j++) {
if (this.afterData[j].name == this.beforeData[i].name) {
this.afterData[j].origin.push(this.beforeData[i]);
break;
}
}
}
}

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