Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge object nested arrays into a single new array

Given the object below, I'm looking for a clean and efficient way to create an array from each item's "subItems" array.

const items = [{
    'a': 'a1',
    'b': 'b1',
    'subItems': [
        {'c': 'c1'},
        {'d': 'd1'}
    ]
  },
  {
    'e': 'e1',
    'subItems': [
      {'f': 'f1'},
      {'g': 'g1'}
    ]
  }
];

So for this example, the result I would need is:

const groupedSubItems = [{c: c1},{d:d1},{f:f1},{g:g1}];

Currently I'm just looping through and concatting all the arrays but it does not feel like the best way to handle this:

let groupedSubItems = [];
items.forEach(function(item) {
  if (item.subItems) {
    groupedSubItems = groupedSubItems.concat(item.subItems);
  }
});

Note: All subitems arrays will only be one level down as shown, with the same key, and may or may not exist.

like image 472
DasBeasto Avatar asked Feb 07 '26 23:02

DasBeasto


2 Answers

You can use concat with spread syntax and map method to create array of subitems.

const items = [{"a":"a1","b":"b1","subItems":[{"c":"c1"},{"d":"d1"}]},{"e":"e1","subItems":[{"f":"f1"},{"g":"g1"}]}]

const subItems = [].concat(...items.map(({subItems}) => subItems || []));
console.log(subItems)
like image 91
Nenad Vracar Avatar answered Feb 09 '26 11:02

Nenad Vracar


First you want to get only the subitems:

var itemsSubItems = items.map(function(item) { return item.subItems; });
// [ [ { item: 1 }, { item: 2 } ], [ { item: 3 } ] ]

This gives you an array of arrays. Each element in the array still represents an item: the sub items of that item. You now want just the array of subitems though, not delimited by item.

var subItems = itemsSubItems.reduce(function(si, current) {
  return si.concat(current);
}, []);

For each array-of-subitems in the outer array, concatenate them to a new array.

A shorter ES6 example:

const subItems = items.map(item => item.subItems).reduce((a, c) => a.concat(c), []);
like image 24
Charles Stover Avatar answered Feb 09 '26 12:02

Charles Stover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!