我有两个数组,它们具有非常大但数量未知的对象。例如:
const x = [
{
id:'apples',
oldData: {
min: 9,
max: 50
}
},
...
]
const y = [
{
id:'bananas',
newData: {
min: 2,
max: 60
}
},
{
id:'apples',
newData: {
min: 50,
max: 200
}
},
...
]
我需要结合这些,所以我的结果是这样的:
const x = [
{
id:'apples',
oldData: {
min: 9,
max: 50
},
newData: {
min: 50,
max: 200
}
},
{
id:'bananas',
newData: {
min: 2,
max: 60
}
}
...
]
请注意,apples 被合并以包含来自两个数组的数据,bananas 被添加为一个新元素,因为它没有匹配项。每个数组可能有数百个值,所以我发现执行 .map()
和 Object.keys().map()
非常昂贵。
使用 ES6 并导入 Lodash。
最佳答案
你可以试试看
const x = [{id:'apples',oldData: {min: 9,max: 50}}];
const y = [{id:'bananas',newData: {min: 2,max: 60}},{id:'apples',newData: {min: 50,max: 200}}];
// Create an object with id as key and object as value
let obj = x.reduce((a,c) => Object.assign(a, {[c.id]:c}), {});
// Updating the value of object and adding new entries
y.forEach(v => {
if(obj[v.id]) obj[v.id].newData = v.newData;
else obj[v.id] = v;
});
// Getting the values in the object
console.log(Object.values(obj));
关于javascript - 将对象数组与相似数据合并的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52336497/