Akhoy Akhoy - 6 months ago 11
Javascript Question

Array of JavaScript objects from JSON

I have a deeply nested JSON structure as below:

[
{
"ATA": "49",
"Description": "APU",
"MSI": "",
"Level":"1",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-10",
"Description": "Power Plant",
"MSI": "",
"Level":"2",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13",
"Description": "APU Mounts",
"MSI": "Yes",
"Level":"3",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13-01",
"Description": "APU Gearbox Mount Bracket",
"MSI": "Yes",
"Level":"4"
}]
}
}
]
}
}
]
}
}

]


I'm trying to convert the following into an array of the form for easier processing of this data to show in a tabular format:

[{ATA:"49",Description:"APU",MSI:""},{ATA:"49-10",Description:"PowerPlant",MSI:""}]...


I've tried a lot of ways and though I can get all the key / value pairs, I can't figure out how to do this. I can't change the JSON since all the child nodes have dependencies. Any ideas?

Edit: I tried the following solution to get all key / value pairs: Traverse all the Nodes of a JSON Object Tree with JavaScript but I can't find out when to start a new object.

Answer

You should use a recursive function for this:

function processNodes(nodes, output){
    for (var i = 0, l = nodes.length; i < l; ++i){
        output.push({
            "ATA": nodes[i]["ATA"],
            "Description": nodes[i]["Description"],
            "MSI": nodes[i]["MSI"]
        });
        if (nodes[i]["ChildNodes"]){
            processNodes(nodes[i]["ChildNodes"]["Nodes"], output);
        }
    }
}

Then:

var json = JSON.parse( ... );
var output = [];
processNodes(json, output);
console.log(output);