Skip to content

Instantly share code, notes, and snippets.

@mahmoud-eskandari
Created April 16, 2020 17:11
Show Gist options
  • Save mahmoud-eskandari/d595e8a1dab25450a66f66beecea4e00 to your computer and use it in GitHub Desktop.
Save mahmoud-eskandari/d595e8a1dab25450a66f66beecea4e00 to your computer and use it in GitHub Desktop.
flatten nested array of objects by a key
function flattenMap(itemList, key) {
return itemList.flatMap(item => {
if (typeof item[key] === 'undefined' || item[key].length === 0) {
return item;
}
let childs = item[key];
delete item[key];
return [item, ...flattenMap(childs, key)];
});
}
// example
let myMap = [
{a:1,lists:[{a:2},{a:3}]},
{a:4,lists:[{a:5},{a:6,lists:[{a:61,lists:[{a:611},{a:612}]}]}]},
{a:7}
];
console.log(flattenMap(myMap,'lists'));
// Out
[{a: 1},
{a: 2},
{a: 3},
{a: 4},
{a: 5},
{a: 6},
{a: 61},
{a: 611},
{a: 612},
{a: 7}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment