Tsu Anthony Tsu Anthony - 5 months ago 11
JSON Question

How Can I Get the Navigation Path of a Node in a JSON Tree While Iterating Through the Tree

JSON Excerpt:

{
"a": {
"b1" : {
"c1" : {
"d1" : "D1",
"d2" : "D2",
"d3" : "D3"
},
"c2" : {
"d4" : "D4",
"d5" : "D5"
}
},
"b2" : {
"c3" : {
"d6" : D6
}
}
}
}


I would like to iterate the JSON Tree and obtain a list of 'd' series values with the navigation path of each 'd' node, such as

[{'name': 'd1', 'value': 'D1', 'path': ['a', 'b1', 'c1']},...]


Here, I wrote a function as follows:

function GetParameters(obj) {
for (var sProp in obj) {
if(typeof(obj[sProp]) == "string") {
parameters.push({'name':sProp,'value':obj[sProp]})
} else {
GetParameters(obj[sProp]);
}
}
}


This function only generate the 'name' and 'value' parts of each 'd' record, but how can I get the 'path' part done in this function?

Any workarounds are welcomed. Thanks!

Answer

You could use an iterative and recursive approach with supplying the actual path to the next recursion.

If an end node is found, then a new object is pushed to the result array with the visited nodes.

function getPath(object) {

    function iter(o, path) {
        Object.keys(o).forEach(function (k) {
            if (typeof o[k] === 'object') {
                return iter(o[k], path.concat(k));
            }
            result.push({ name: k, value: o[k], path: path });
        });
    }

    var result = [];
    iter(object, []);
    return result;
}

var data = { "a": { "b1": { "c1": { "d1": "D1", "d2": "D2", "d3": "D3" }, "c2": { "d4": "D4", "d5": "D5" } }, "b2": { "c3": { "d6": "D6" } } } };

console.log(getPath(data));

Comments