0

I would like to use node.js to loop through all values in a JSON structure.

My code looks like this:

var data = {
    "nodes": [
        { "name": "Folder 1" },
        { "name": "Folder 2" },
        { "name": "Folder 3" },
        {
            "name": "Folder 4",
            "nodes": [
                { "name": "Folder 4.1" },
                {
                    "name": "Folder 4.2",
                    "nodes": [
                        { "name": "Folder 4.2.1" },
                        { "name": "Folder 4.2.2" },
                        { "name": "Folder 4.2.3" }
                    ]
                },
                { "name": "Folder 4.3" }
            ]
        },
        { "name": "Folder 5" }
    ]

};

function iterateNodes(data) {
    for (var i = 0, l = data.nodes.length; i < l; i++) {
        var node = data.nodes[i];

        console.log(node.name);


        if (node.nodes) {
            arguments.callee(node);
        }
    }
}

iterateNodes(data);

that works except I would like it to display "name:Folder 1". I would also like to replace the word name in the log statement so that It doesn't rely on a single JSON structure. I need it to support any structure.

How could i go about doing this?

Also. I found this stack overflow question similar to mine, but I can't find a way to adapt it. to fit my needs.

Community
  • 1
  • 1
Wendell Blatt
  • 177
  • 1
  • 1
  • 10
  • You mean you want `iterateNodes` to accepts an argument which specifies with property to display? – Felix Kling Dec 26 '13 at 21:26
  • That would work as long as I could write it in such a way that it could call itself again if the next "lowest" property contained more than one property. If you know what I mean, sorry if I'm unclear. – Wendell Blatt Dec 26 '13 at 21:28
  • Don't you already have that? `if (node.nodes) { arguments.callee(node); }` – Felix Kling Dec 26 '13 at 21:34
  • possible duplicate of [Loop through JavaScript object](http://stackoverflow.com/questions/684672/loop-through-javascript-object) – Qantas 94 Heavy Feb 09 '14 at 09:07

0 Answers0