Last active
November 17, 2018 20:11
-
-
Save steinfletcher/9989929 to your computer and use it in GitHub Desktop.
Object tree traversal in javascript (with lodash)
This file contains hidden or 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(obj[key])) { | |
traverse(obj[key]); | |
} | |
}); | |
} |
You should not need to check for isObject
inside the isArray
function traverse (obj, cb) {
_.forEach(obj, function (val, key) {
cb(val, key);
if (_.isObject(val) || _.isArray(val)) traverse(val, cb);
});
}
e.g. traverse(data, (val, key) => console.log(val, key))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to replace:
With:
In order to get it to traverse descendant objects.