Skip to content

Instantly share code, notes, and snippets.

@tusharf5
Created July 17, 2019 19:58
Show Gist options
  • Save tusharf5/0808717f12c17a4e0990248a2cb45c7b to your computer and use it in GitHub Desktop.
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
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