以递归方式从Javascript / jQuery中获取嵌套JSON中的所有子项

时间:2013-06-06 17:11:50

标签: javascript jquery json

我得到了一些嵌套的JSON,如下所示:

[
{"ID": 1,
 "Name": "This is a Catogory, i don´t need them",
 "Items": [
          {"ID": 2,
           "Name": "Some String here",
           "Items": [{
               "ID": 2,
               "Name": "Some String here",
                ... etc ...
          },
          },
          {"ID": 5,
           "Name": "Some String here"
          },
          {"ID": 3,
           "Name": "Some String here"
          },
          {"ID": 4,
           "Name": "Some String here"
          }
          ]
},
...
]

现在我需要将所有带有名称和ID的子项保存到字典中,并将ID作为密钥。

这应该与我认为的递归方法有关。不确切知道如何,我只获得所有项目或只获得子项目中的第一项: - /
对于一些简单的代码,一个很好的链接或其他什么我将不胜感激。

抱歉,我认为这还不够清楚。子项目也可以有子项目!
我对嵌套结构没有影响。

1 个答案:

答案 0 :(得分:1)

如果对象的深度未知,您将需要一个递归函数来提取所需的数据。

var test = [
    {
        "ID": 1,
        "Name": "This is a Catogory, i don´t need them",
        "Items": [
            {
                "ID": 2,
                "Name": "Some String here",
                "Items": [
                    {
                        "ID": 12,
                        "Name": "Some String here"
                    },
                    {
                        "ID": 13,
                        "Name": "Some String here"
                    }
                ]
            },
            {
                "ID": 5,
                "Name": "Some String here"
            },
            {
                "ID": 3,
                "Name": "Some String here"
            },
            {
                "ID": 4,
                "Name": "Some String here"
            }
        ]
    },
    {
        "ID": 1,
        "Name": "This is a Catogory, i don´t need them",
        "Items": [
            {
                "ID": 7,
                "Name": "Some String here"
            },
            {
                "ID": 8,
                "Name": "Some String here"
            },
            {
                "ID": 9,
                "Name": "Some String here"
            },
            {
                "ID": 10,
                "Name": "Some String here"
            }
        ]
    }
]

var kvp = [];
function parseItems(startArray)
{
    console.log(startArray);
    if(startArray === undefined)
        return;
    for (var i = 0, l = startArray.length; i < l; i++) {
        if(startArray[i].Items === undefined)
                continue;
        for (var j = 0, k = startArray[i].Items.length; j < k; j++) {
            kvp[startArray[i].Items[j].ID] = startArray[i].Items[j].Name;
            parseItems(startArray[i].Items);
        }
    }
}

console.log(kvp);

这将打印出类似这样的内容:

[
    2: "Some String here",
    3: "Some String here",
    4: "Some String here",
    5: "Some String here",
    7: "Some String here",
    8: "Some String here",
    9: "Some String here",
    10: "Some String here",
    12: "Some String here",
    13: "Some String here"
]

Here是一个jsfiddle示例