我很难找到与Lodash和Underscore进行多级推送/合并的解决方案。尝试避免使用JS进行一些混乱的嵌套循环。
这是我如何合并的示例。
const arr = [
{
level : 'test',
items : [1, 2, 3]
},
{
level : 'tests',
items : [1, 2, 3]
}
];
const obj = {
level : 'test',
items : [4, 5, 6]
};
/* Output:
[
{
level : 'test',
items : [1, 2, 3, 4, 5, 6]
},
{
level : 'tests',
items : [1, 2, 3]
}
];
*/
obj
级别与arr[0]
匹配,因此items数组应合并。新的或唯一的级别应作为新对象推送到数组。有没有一种方法可以通过Lodash的_.groupBy和_.mergeWith的某种组合来实现?到目前为止,我已经将其合并到具有两个分别来自两个唯一级别的两个对象的单个数组中,但是当items数组合并时,它以
[4, 5, 6]
结尾。任何帮助,将不胜感激。
最佳答案
您可以使用array#find
搜索具有相同level
值的对象。然后,成功匹配array#concat
个项目。
const arr = [ { level : 'test', items : [1, 2, 3] }, { level : 'tests', items : [1, 2, 3] } ];
const obj = { level : 'test', items : [4, 5, 6] };
const result = arr.find(o => o.level === obj.level);
if(result)
result.items = result.items.concat(obj.items);
console.log(arr);