JD_Coder JD_Coder - 1 year ago 131
JSON Question

Iterate over unlimited nested json structure

Hi I have a JSON which is nested and can also have unlimited hierarchy. Below is the structure of JSON -

[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
"children": [{
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12,
"children": [{
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}, {
"name": "child 2",
"id": 16,
"ParentId": 13,
"leaf": true
}]
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 14,
"ParentId": 12,
"children": [{
"name": "child 1",
"id": 17,
"ParentId": 14,
"leaf": true
}, {
"name": "child 2",
"id": 18,
"ParentId": 14,
"leaf": true
}]
}]
}]


and I want the output to be as -

[
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 2",
"id": 16,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}]
]


Any help is appreciated.

Answer Source

You could store the path to the leafes and push the path then to the result set.

function getValues(array) {
    var result = [];

    array.forEach(function iter(path) {
        return function (o) {
            var temp = path.concat({ name: o.name, leaf: o.leaf, id: o.id, ParentId: o.ParentId });
            if (o.children) {
                o.children.forEach(iter(temp));
                return;
            }
            result.push(temp);
        };
    }([]));

    return result;
}

var data = [{ name: "Main", leaf: false, id: 12, ParentId: null, children: [{ name: "Sub Main 1", leaf: false, id: 13, ParentId: 12, children: [{ name: "child 1", id: 15, ParentId: 13, leaf: true }, { name: "child 2", id: 16, ParentId: 13, leaf: true }] }, { name: "Sub Main 2", leaf: false, id: 14, ParentId: 12, children: [{ name: "child 1", id: 17, ParentId: 14, leaf: true }, { name: "child 2", id: 18, ParentId: 14, leaf: true }] }] }],
    result = getValues(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download