遍历JSON树并操纵其数据/结构

时间:2014-10-29 08:26:49

标签: javascript jquery json

我正在尝试创建一个可以遍历JSON树并更改其数据/结构的函数。我设法让它遍历每个节点并读取数据,但坚持改变其数据/结构部分。

function jsonTraverser(tree){
    $.each(tree, function(index, val){
        if(val.tag == 'button'){
            delete val[index];
        }
        if(val.children){
            jsonTraverser(val.children);
        }
    })
}
jsonTraverser(json_obj);

从上面的代码中,它应该删除标记等于按钮的JSON节点。虽然它似乎有效,但它不会删除节点,而更改其标签工作得很好。你有解决这个问题的方法吗?

PS:如果你需要JSON树的样本,这里就是。

[
  {"tag":"div","id":"0","class":"sgph","children":[
    {"tag":"div","data-scoretype":"","class":"sgi","id":"1","children":[
      {"tag":"button","data-btnrole":"satis_group","class":"up","html":"ขึ้น"},
      {"tag":"button","data-btnrole":"satis_group","class":"down","html":"ลง"},
      {"tag":"button","data-btnrole":"satis_group","class":"edit","html":"เปลี่ยนกลุ่ม"},
      {"tag":"button","data-btnrole":"satis_group","class":"del","html":"ลบกลุ่ม"}
    ]},
    {"tag":"div","class":"scph","children":[
      {"tag":"button","data-btnrole":"score_type","class":"add","html":"เกณฑ์การให้คะแนน"}
    ]},
    {"tag":"div","class":"stph","children":[
      {"tag":"div","class":"sti","id":"3","children":[
          {"tag":"button","data-btnrole":"satis_topics","class":"up","html":"ขึ้น"},
          {"tag":"button","data-btnrole":"satis_topics","class":"down","html":"ลง"},
          {"tag":"button","data-btnrole":"satis_topics","class":"edit","html":"เปลี่ยนหัวข้อ"},
          {"tag":"button","data-btnrole":"satis_topics","class":"del","html":"ลบหัวข้อ"}
        ]},
      {"tag":"button","data-btnrole":"satis_topics","class":"add","html":"เพิ่มหัวข้อ"}
    ]}
  ]},
  {"tag":"div","id":"1","class":"sgph","children":[
    {"tag":"button","data-btnrole":"satis_group","class":"add","html":"เพิ่มกลุ่ม"}
  ]}
]  

1 个答案:

答案 0 :(得分:0)

你拼错了一些变量名。例如," v"应该是" val"。 jsonTraverse也应该来自树而不是来自val的delete,因为树拥有孩子的列表。

function jsonTraverser(tree){
    $.each(tree, function(index, val){
        if(val.tag == 'button'){
            delete tree[index];
        }
        if(val.children){
            jsonTraverser(val.children);
        }
    })
}

请注意,您必须处理根本身有标记'按钮的情况。