【发布时间】:2018-08-15 23:00:33
【问题描述】:
我发现很难找到一个解决方案,用于与 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 的某种组合来实现这一点?到目前为止,我已经将它合并到一个数组中,其中包含来自两个各自唯一级别的两个对象,但是当项目数组合并时,它以 [4, 5, 6] 结束。
任何帮助将不胜感激。
【问题讨论】:
标签: javascript arrays underscore.js lodash