迭代JSON对象并形成所有嵌套组合

时间:2015-08-13 11:31:55

标签: javascript json

我有一个JSON对象,如下所示。我想遍历所有对象及其子项并形成所有可能的嵌套组名称:示例在下面给出。

{
    "groups": [
        {
            "group": "group1",
            "childrens": [
                {
                    "group": "group1_1",
                    "childrens": []
                },
                {
                    "group": "group1_2",
                    "childrens": [
                        {
                            "group": "group1_2_1",
                            "childrens": []
                        },
                        {
                            "group": "group1_2_2",
                            "childrens": []
                        },
                        {
                            "group": "group1_2_3",
                            "childrens": []
                        }
                    ]
                },
                {
                    "group": "group1_3",
                    "childrens": []
                },
                {
                    "group": "group1_4",
                    "childrens": []
                }
            ]
        },
        {
            "group": "group2",
            "childrens": [
                {
                    "group": "group2_1",
                    "childrens": []
                },
                {
                    "group": "group2_2",
                    "childrens": []
                }
            ]
        }
    ]
}


Q) how to genarete the below list from above JSON
  group1
  group1/group1_1
  group1/group1_2
  group1/group1_2/group1_2_1
  group1/group1_2/group1_2_2
  group1/group1_2/group1_2_3
  group1/group1_3
  group1/group1_4
  group2
  group2/group2_1
  group2/group2_2

我有一个JSON对象,如下所示。我希望遍历所有对象及其子代,并形成所有可能的嵌套组名。

1 个答案:

答案 0 :(得分:0)

这样的事情能为你效劳吗?

for(var i in OBJECT){
   iterate(OBJECT[i]);
}

function iterate(item){

    for(var i in item){
       if(typeof item[i] == "object"){
           iterate(item[i]);
       }else{
           doAction();
       }
    }

    var doAction = function(){
       ///// WHATEVER ACTION
    }

}