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.