Created
July 17, 2019 19:58
-
-
Save tusharf5/0808717f12c17a4e0990248a2cb45c7b to your computer and use it in GitHub Desktop.
Javascript function to iterate and modify all the nodes in a tree like javascript object
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
let obj = { | |
id: '1', | |
children: [ | |
{ | |
id: '2', | |
children: [ | |
{ | |
id: '4', | |
children: [ | |
{ | |
id: '5', | |
children: [ | |
{ | |
id: '6', | |
}, | |
{ | |
id: '7', | |
} | |
] | |
} | |
] | |
} | |
] | |
}, | |
{ | |
id: '3', | |
} | |
] | |
}; | |
function mapTree(obj, mapFunction) { | |
mapFunction(obj); | |
if(obj.children) { | |
obj.children.forEach((child, index) => { | |
mapOverArray(child, mapFunction); | |
}); | |
} | |
} | |
function modifyObject(obj) { | |
obj.hello = obj.id + '_extended'; | |
obj.newProp = 'yeaah'; | |
}; | |
mapTree(obj, modifyObject); | |
console.log(JSON.stringify(obj, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment