简体   繁体   中英

Merge nested array of objects by unique property and array

I am finding a difficult time finding a solution for multiple levels of push / merging with Lodash and Underscore. Trying to avoid some messy nested loops with JS.

Here's an example of how I need to merge.

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]
    }
  ];
*/

The obj level matches arr[0] , and so the items array should merge. New, or unique levels should push to the array as a new object.

Is there a way I could achieve this through some combination of _.groupBy and _.mergeWith of Lodash? So far, I have gotten it to merge into a single array with two objects from the two respective unique levels, but when the items arrays merge it ends up with [4, 5, 6] .

Any help would be appreciated.

You can use array#find to search for an object with same level value. Then, for a successful match array#concat items.

 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})

让我知道是否有效

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM