謝謝大家的反饋,因爲這是我的第一個問題。我會再嘗試。獲取節點的JSON父節點
我有一個JSON對象,例如:
var obj = {
"data":[
{
"data":{
"title":"title1",
"attr":{
"id":111
}
},
"children":[
{
"data":{
"title":"title2",
"attr":{
"id":222
}
},
"children":[
{
"data":{
"title":"title3",
"attr":{
"id":333
}
}
}
]
},
{
"data":{
"title":"title4",
"attr":{
"id":444
}
},
"children":[
{
"data":{
"title":"title5",
"attr":{
"id":555
}
}
}
]
}
]
}
]
};
帶給定值的ID,我想通過標題屬性,以追蹤「血統」,以它爲:給222,我應該得到冠軍1;給定id 333,我應該得到title1> title 2;給予id 555,我應該得到title1> title 4.請注意,這些不是父母,而是父母的兄弟姐妹,因爲每個數據對象都與一組「children」對象配對。
我試過如下:
var x = 555;
var path = "";
function search(path, obj, target) {
for (var k in obj) {
if (obj[k] === target) {
return path + "['" + k + "']"
}
else if (typeof obj[k] === "object") {
var result = search(path + "['" + [k] + "']", obj[k], target);
if (result)
return result;
}
}
return false;
}
var path = search(path, obj, x);
console.log(path); // "['data']['0']['children']['1']['children']['0']['data']['attr']['id']"
,但我沒能拿到冠軍的屬性返回。任何幫助將不勝感激,並感謝大家的耐心。
你做出什麼樣的努力? –
用以前的評論:http://stackoverflow.com/help/how-to-ask – Jan