2014-09-20 88 views
-1

我的嵌套JSON的樣子:獲得JSON對象父母ID列表

var obj ={ "Name": "Main", "Id": "1", "Parent": "0", "children": [{ "Name": "Main1", "Id": "2", "Parent": "1", "children": [ ... 

obj是樹狀結構,看起來像這樣:

enter image description here

如何解析OBJ得到指定ID的任何父母的ID?

例如一個jquery函數function getIdParentsOf('25') { }

輸出是例如:25父母直到1是{20, 18, 10, 1 }

+1

你是什麼意思* 「讓我的某個ID的父母的ID?」 *?示例json中的'id' 25在哪裏?如何通過25返回結果*直到1 *? 1從哪裏來?你的問題完全不清楚。 – 2014-09-20 07:54:06

+0

不好意思。我的英語不是很好。看到這個鏈接:http://upload7.ir/imgs/2014-09/97877257812703750606.png – hahamed 2014-09-20 08:33:36

回答

2

該聲明只是一個具有特定屬性的對象,包括相同類型的子節點數組。基本上是一個樹形結構

你已經更新了問題,現在樹是分層的。這意味着你需要遞歸地走樹。的jsfiddle:http://jsfiddle.net/TrueBlueAussie/gdwjmqwh/6/

// If the required node is found, return true 
// matching nodes added to the result parameter 
var findParent = function (parentnode, id, result) { 
    if (parentnode.Id == id){ 
     result.push(parentnode.Parent); 
     return true; 
    } 
    if (parentnode.children) { 
     for (var i = 0; i < parentnode.children.length; i++) { 
      var node = parentnode.children[i]; 
      if (parentnode.Parent && findParent(node, id, result)) { 
       result.push(parentnode.Parent); 
       return true; 
      } 
     } 
    } 
    // no matches found - return false 
    return false; 
} 

這樣調用

var result = []; 
findParent(obj, "2", result) 
console.log(result); 
// Displays an array of parent ids