-1

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.

Community
  • 1
  • 1
Akhoy
  • 502
  • 1
  • 13
  • 24

1 Answers1

3

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);
Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
  • Is there a way to pass the parent node to the object before pushing it into output array? – Akhoy Jun 01 '16 at 07:25
  • @Akhoy That depends … How do you want to 'store' this parent node? The full node, with all its parent hierarchy? Just the node itself? Would an id string do? – Aurel Bílý Jun 02 '16 at 10:53
  • @AurelBílý thanks. I implemented what I wanted to do. – Akhoy Jun 06 '16 at 11:33