[英]Merge nested array of objects by unique property and array
我很难找到一个与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);
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] } ]; */ const newArr = _.map(arr, (val) => { return !_.isEqual(val.level, obj.level) ? val : _.assign({}, val, { items: _.concat(val.items, obj.items) }); }); console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
arr.map((e)=>{e.level === obj.level && e.items.push(...obj.items);return e})
让我知道是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.