Created
April 16, 2020 17:11
-
-
Save mahmoud-eskandari/d595e8a1dab25450a66f66beecea4e00 to your computer and use it in GitHub Desktop.
flatten nested array of objects by a key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)]; | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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