2015-06-21 249 views
0

謝謝大家的反饋,因爲這是我的第一個問題。我會再嘗試。獲取節點的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']" 

,但我沒能拿到冠軍的屬性返回。任何幫助將不勝感激,並感謝大家的耐心。

+1

你做出什麼樣的努力? –

+1

用以前的評論:http://stackoverflow.com/help/how-to-ask – Jan

回答

0

通過使用循環以查找指定的可以嘗試的項目:

var obj={"data":[{"data":{"title":"title1","attr":{"id":111}},"children":[{"data":{"title":"title2","attr":{"id":222}},"children":[{"data":{"title":"title3","attr":{"id":333}},"children":[{"data":{"title":"title4","attr":{"id":444}},"children":[{"data":{"title":"title5","attr":{"id":555}},"children":[]}]}]}]}]}]} 
 

 
var current = obj.data[0], titles = []; 
 

 
while(current.data && current.data.attr.id != 444){ 
 
\t titles.push(current.data.title); 
 
\t current = current.children[0] || {} 
 
} 
 

 
document.write(titles.join(" > "));

+0

謝謝,但如果我的樹有兄弟姐妹,就像我上面的新例子,這個答案會失敗。我嘗試瞭解它,但無法提出解決方案,請參閱我所嘗試的內容。再次感謝! – levProg