使用相同的键(javascript)将属性从一个数组添加到另一个数组 [英] Add property from one array into another array with the same key (javascript)
问题描述
您好,而不是用文字解释它我刚刚在下面做了一个快速的视觉表示。
Hello instead of explaining it in words I've just made a quick visual representation below.
说我有以下数组:
let arr1 = [
{
id: 1,
someKey: someValue
},
{
id: 2,
someKey: someValue
},
]
和另一个数组:
let arr2 = [
{
id: 1,
numberOfItems: 10
},
{
id: 2,
numberOfItems: 20
},
]
我如何创建以下数组?
let result = [
{
id: 1,
someKey: someValue,
numberOfItems: 10
},
{
id: 2,
someKey: someValue,
numberOfItems: 10
},
]
正如您所看到的,两个数组都具有相同的 id
值。我想从第二个数组中取 numberOfItems:10
并将它放在同一个id下的第一个数组中。
So as you can see, both arrays have the same id
value. I want to take numberOfItems: 10
from the second array and place it into the first array under the same id.
注意:两个ID完全不同,具有不同的属性和长度。唯一的相似之处是 id
Note: the two ids are completely different, have different properties and length. The only similarity is the id
谢谢!
推荐答案
您可以先创建一个id为key的地图,然后合并对象这将解决O(n)中的问题:
You could first create a map with id as key and then combine the objects This would solve the problem in O(n):
let arr1 = [
{
id: 1,
someKey: 3
},
{
id: 2,
someKey: 6
},
];
let arr2 = [
{
id: 1,
numberOfItems: 10
},
{
id: 2,
numberOfItems: 20
},
];
let arr2Map = arr2.reduce((acc, curr) => {
acc[curr.id] = curr
return acc;
}, {});
let combined = arr1.map(d => Object.assign(d, arr2Map[d.id]));
console.log(combined);
这篇关于使用相同的键(javascript)将属性从一个数组添加到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!