通过相同的键组合多个数组 [英] Combine multiple arrays by same key
本文介绍了通过相同的键组合多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过特定的 key
属性组合多个数组.例如,我有
I'm trying combine multiple arrays by a specific key
property. For example, I have
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'}]
}]
推荐答案
可以使用这样的哈希表:
May use a hash table like this:
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;
};
这篇关于通过相同的键组合多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文