Skip to content

Instantly share code, notes, and snippets.

@victorzhuk
Forked from tushar-borole/traverse.js
Created October 5, 2018 23:54
Show Gist options
  • Save victorzhuk/ae341bf942e8f14b65c45958a6bde385 to your computer and use it in GitHub Desktop.
Save victorzhuk/ae341bf942e8f14b65c45958a6bde385 to your computer and use it in GitHub Desktop.
Object tree traversal in javascript (with lodash)
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]);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment