js将数组对象中某个值相同的对象合并成一个新对象
Posted yihengbaobei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js将数组对象中某个值相同的对象合并成一个新对象相关的知识,希望对你有一定的参考价值。
原数组:
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" }]} ]
实现方法:
第一种方法:
var afterData = [] 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);
第二种方法:
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)
以上是关于js将数组对象中某个值相同的对象合并成一个新对象的主要内容,如果未能解决你的问题,请参考以下文章
将两个数组相同index的value合并成一个新的value组成一个新的数组