Skip to content

Instantly share code, notes, and snippets.

@steinfletcher
Last active November 17, 2018 20:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steinfletcher/9989929 to your computer and use it in GitHub Desktop.
Save steinfletcher/9989929 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(obj[key])) {
traverse(obj[key]);
}
});
}
@BobDickinson
Copy link

I had to replace:

    if (_.isObject(key)) {

With:

    if (_.isObject(obj[key])) {

In order to get it to traverse descendant objects.

@YemSalat
Copy link

YemSalat commented Jul 15, 2016

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