js将数组对象中某个值相同的对象合并成一个新对象
2021-01-16 01:12
标签:each items foreach dex length map find bsp i++ 原数组: 最终数组: 实现方法: 第一种方法: 第二种方法: 第三种方法: js将数组对象中某个值相同的对象合并成一个新对象 标签:each items foreach dex length map find bsp i++ 原文地址:https://www.cnblogs.com/yihengbaobei/p/12933512.htmlvar 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" }]}
]
var afterData = []
let tempArr = []
for (let i = 0; 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);
let afterData = []
let tempArr = []
beforeData.map(item => {
if (tempArr.indexOf(item.name) === -1) {
afterData.push({
name: item.name,
origin: []
});
tempArr.push(item.name)
}
});
afterData.map(item => {
beforeData.map(items => {
if (item.name == items.name) {
item.origin.push(items)
}
})
})
console.log(afterData)
var afterData = []
beforeData.forEach(item => {
let flag = afterData.find(item1 => item1.name === item.name)
if (!flag) {
afterData.push({
name: item.name,
origin: [item]
})
} else {
flag.origin.push(item)
}
})
console.log(afterData)
上一篇:Java学习路线导航图
文章标题:js将数组对象中某个值相同的对象合并成一个新对象
文章链接:http://soscw.com/index.php/essay/42484.html