-
-
Save tushar-borole/567c1d22ca8d5498cbc0 to your computer and use it in GitHub Desktop.
Object tree traversal in javascript (with lodash)
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
var data = { | |
"name": "root", | |
"contents": [ | |
{ | |
"name": "A", | |
"contents": [ | |
{ | |
"name": "fileA1", | |
"contents": [] | |
} | |
] | |
}, | |
{ | |
"name": "B", | |
"contents": [ | |
{ | |
"name": "dirB1", | |
"contents": [ | |
{ | |
"name": "fileBB1", | |
"contents": [] | |
} | |
] | |
}, | |
{ | |
"name": "fileB1", | |
"contents": [] | |
} | |
] | |
} | |
] | |
}; | |
traverse(data); | |
function traverse(obj) { | |
_.forIn(obj, function (val, key) { | |
console.log(key, val); | |
if (_.isArray(val)) { | |
val.forEach(function(el) { | |
if (_.isObject(el)) { | |
traverse(el); | |
} | |
}); | |
} | |
if (_.isObject(key)) { | |
traverse(obj[key]); | |
} | |
}); | |
} |
sykire
commented
May 16, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment