gpt4 book ai didi

javascript - 通过相同的键组合多个数组

转载 作者:行者123 更新时间:2023-11-28 17:53:08 24 4
gpt4 key购买 nike

我正在尝试按特定的 key 组合多个数组属性(property)。例如,我有

arr1

  [{
key: 'A',
items: [{name: 'a item'}]
}, {
key: 'B',
items: [{name: 'b item'}]
}]

arr2

  [{
key: 'B',
items: [{name: 'another b item'}, {name: 'more b items'}, {name: 'even more b items'}]
}]

如何生成以下arr3

  [{
key: 'A',
items: [{name: 'a item'}]
},
{
key: 'B',
items: [{name: 'b item'}, {name: 'another b item'}, {name: 'more b items'}, {name: 'even more b items'}]
}]

最佳答案

可以使用这样的哈希表:

arr1=[{
key: 'A',
items: [{name: 'a item'}]
}, {
key: 'B',
items: [{name: 'b item'}]
}];

arr2=[{
key: 'B',
items: [{name: 'another b item'}, {name: 'more b items'}, {name: 'even more b items'}]
}];

console.log(arr1.concat(arr2).reduce((function(hash){
return function(array,obj){
if(!hash[obj.key])
array.push(hash[obj.key]=obj);
else
hash[obj.key].items.push(...obj.items);
return array;
};

})({}),[]));

一些解释:

arr1.concat(arr2)//just work with one array as its easier
.reduce(...,[]));//reduce this array to the resulting array
//through
(function(hash){//an IIFE to closure our hash object
...
})({})
//which evaluates to
function(array,obj){//take the resulting array and one object of the input
if(!hash[obj.key])//if we dont have the key yet
array.push(hash[obj.key]=obj);//init the object and add to our result
else
hash[obj.key].items.push(...obj.items);//simply concat the items
return array;
};

关于javascript - 通过相同的键组合多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com