通过属性查找重复的对象并使用Javascript或UnderscoreJS进行合并 [英] Find duplicate object by property and Merge using Javascript or UnderscoreJS
本文介绍了通过属性查找重复的对象并使用Javascript或UnderscoreJS进行合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所述的数组:
I have an array as mentioned below:
var somevalue = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
]
我要从此数组中按 code
查找重复的元素,并将同一代码的所有元素合并为一个.因此,最终输出将是:
From this array, I want to find duplicate element by code
and merge all elements of the same code into one. So the final output would be:
var somevalue = [{
code: 1,
name: 'a1, a2'
}, {
code: 2,
name: 'b1, b2, b3'
}
]
有什么方法可以使用 underscoreJS
来实现?
is there any way to achieve this using underscoreJS
?
我可以通过 for-loop
来做到这一点.但是在实际情况下,其非常大的数组包含具有10个属性的JSON对象.因此,我需要一些面向性能的解决方案.
I can do this by for-loop
. But In real scenario, its very large array containing JSON object of having 10 properties. So I need some performance oriented solution.
推荐答案
您可以使用array.reduce:
You can use array.reduce:
var datas = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
];
datas = datas.reduce((m, o) => {
const found = m.find(e => e.code === o.code);
found ? found.name += `, ${o.name}` : m.push(o);
return m;
}, []);
console.log(datas);
这篇关于通过属性查找重复的对象并使用Javascript或UnderscoreJS进行合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文