我有一个像这样的多个数组的列表
jquery([
{
id:2,
count:23,
numberOfType:34
},
{
id:2,
count2:53,
numberOfType2:34
},
{
id:2,
count3:53,
numberOfType3:34
},
{
id:2,
count:23,
numberOfType:34
},
{
id:21,
count2:53,
numberOfType2:34
},
{
id:21,
count3:53,
numberOfType3:34
},
])
我希望这个数据合成
喜欢
jquery([
{
id:2,
count:23,
count2:53,
count3:53,
numberOfType:34,
numberOfType2:34,
numberOfType3:34
},
{
id:21,
count:23,
count2:53,
count3:53,
numberOfType:34,
numberOfType2:34,
numberOfType3:34
}
])
答案 0 :(得分:3)
通过Array#reduce迭代数组并检查是否存在。如果已存在具有当前项ID的项,则通过Object#assign将属性复制到其中。
const data = [
{
id:2,
count:23,
numberOfType:34
},
{
id:2,
count2:53,
numberOfType2:34
},
{
id:2,
count3:53,
numberOfType3:34
},
{
id:2,
count:23,
numberOfType:34
},
{
id:21,
count2:53,
numberOfType2:34
},
{
id:21,
count3:53,
numberOfType3:34
}
];
const reduced = data.reduce((acc, item) => {
const found = acc.find(i => i.id === item.id);
if(found) {
Object.assign(found, item);
} else {
acc.push(Object.assign({}, item));
}
return acc;
}, []);
console.log(reduced);
答案 1 :(得分:2)
只需使用Object.assign
和Object.values
var output = Object.values( arr.reduce( (a, c) =>
(a[c.id] = Object.assign( {}, a[c.id], c ), a) , //assign new properties to a[c.id]
{} ) ); //accumulator
<强>演示强>
var arr = [{
id: 2,
count: 23,
numberOfType: 34
},
{
id: 2,
count2: 53,
numberOfType2: 34
},
{
id: 2,
count3: 53,
numberOfType3: 34
},
{
id: 2,
count: 23,
numberOfType: 34
},
{
id: 21,
count2: 53,
numberOfType2: 34
},
{
id: 21,
count3: 53,
numberOfType3: 34
},
];
var output = Object.values(arr.reduce((a, c) =>
(a[c.id] = Object.assign({}, a[c.id], c), a), //assign new properties to a[c.id]
{})); //accumulator
console.log( output );
答案 2 :(得分:2)
您可以Map
和id
分组。
var array = [{ id: 2, count: 23, numberOfType: 34 }, { id: 2, count2: 53, numberOfType2: 34 }, { id: 2, count3: 53, numberOfType3: 34 }, { id: 2, count: 23, numberOfType: 34 }, { id: 21, count2: 53, numberOfType2: 34 }, { id: 21, count3: 53, numberOfType3: 34 }],
result = [
...array
.reduce((m, o) => m.set(o.id, Object.assign(m.get(o.id) || {}, o)), new Map)
.values()
];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:1)
您可以使用new Class
并检查累加器中是否存在ID,否则附加
reduce
&#13;