来自JSON的JavaScript对象数组

时间:2016-05-31 17:33:00

标签: javascript json

我有一个深层嵌套的JSON结构,如下所示:

[
    {
    "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"
                                    }]
                            }
                        }
                    ]
                }
            }
        ]
    }        
}

]

我正在尝试将以下内容转换为表单数组,以便更轻松地处理此数据,以表格格式显示:

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

我已经尝试了很多方法,虽然我可以获得所有键/值对,但我无法弄清楚如何做到这一点。我无法更改JSON,因为所有子节点都有依赖项。有什么想法吗?

编辑:我尝试了以下解决方案来获取所有键/值对:Traverse all the Nodes of a JSON Object Tree with JavaScript但我找不到何时开始新对象。

1 个答案:

答案 0 :(得分:3)

你应该使用递归函数:

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);
        }
    }
}

然后:

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