簡體   English   中英

遍歷JSON樹並操縱其數據/結構

[英]Traverse through JSON tree and manipulate its data/structure

我正在嘗試創建一個可以遍歷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);

從上面的代碼中,應刪除標記等於button的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":"เพิ่มกลุ่ม"}
  ]}
]  

您將幾個變量名拼寫錯誤。 例如,“ v”應為“ val”。 jsonTraverse也應該從樹中delete ,而不是從val中delete ,因為樹包含子級列表。

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

請注意,您必須處理根本身具有標簽“ button”的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM