通过 属性 查找重复对象并使用 Javascript 或 UnderscoreJS 合并
Find duplicate object by property and Merge using Javascript or UnderscoreJS
我有一个如下所示的数组:
var somevalue = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
]
从这个数组中,我想通过 code
找到重复的元素,并将相同代码的所有元素合并为一个。所以最终输出将是:
var somevalue = [{
code: 1,
name: 'a1, a2'
}, {
code: 2,
name: 'b1, b2, b3'
}
]
有什么方法可以使用 underscoreJS
来实现吗?
我可以通过 for-loop
做到这一点。但在实际情况下,它的数组非常大,包含 JSON 个具有 10 个属性的对象。所以我需要一些以性能为导向的解决方案。
您可以使用 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);
我有一个如下所示的数组:
var somevalue = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
]
从这个数组中,我想通过 code
找到重复的元素,并将相同代码的所有元素合并为一个。所以最终输出将是:
var somevalue = [{
code: 1,
name: 'a1, a2'
}, {
code: 2,
name: 'b1, b2, b3'
}
]
有什么方法可以使用 underscoreJS
来实现吗?
我可以通过 for-loop
做到这一点。但在实际情况下,它的数组非常大,包含 JSON 个具有 10 个属性的对象。所以我需要一些以性能为导向的解决方案。
您可以使用 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);