-
-
Save alpenzoo/456ed598eab9c748897162fb0da97fe8 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(key)) { | |
| traverse(obj[key]); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment