0
JSON對象:遍歷對象,並建立樹天堂
var json = {
"Tree": [{
"Title": "Condition",
"Attr": {
"Id": 2258,
"Zone": null
},
"Children": [{
"Title": "General Wellness",
"Attr": {
"Id": 2315,
"Zone": null
},
"Children": [{
"Title": "Family Health",
"Attr": {
"Id": 2262,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Home",
"Attr": {
"Id": 2316,
"Zone": null
},
"Children": []
}, {
"Title": "Vitamins",
"Attr": {
"Id": 2317,
"Zone": null
},
"Children": []
}, {
"Title": "Recipes",
"Attr": {
"Id": 2318,
"Zone": null
},
"Children": []
}, {
"Title": "Caregiving",
"Attr": {
"Id": 2325,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Eating",
"Attr": {
"Id": 2346,
"Zone": null
},
"Children": []
}, {
"Title": "Travel Health",
"Attr": {
"Id": 2347,
"Zone": null
},
"Children": []
}]
}]
}]
}
我能夠然而遍歷樹我無法建立一個樹狀結構,例如,如果我想要找「配方」,它應該返回我結果爲:
條件>一般健康>食譜
UPDATE:
穿越通過完成:
function process(key,value) {
alert(key + " : "+value);
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
traverse(o[i],func);
}
}
}
traverse(json,process);
JSON是無效 http://jsonlint.com/驗證這裏。 – Rhea
@depperm增加了遍歷邏輯 –
@Rhea糾正了Json –