2017-04-30 109 views
3

我有以下的JSON:的Javascript遞歸(樹形結構)

var jsonObj = [ 
       { 
         "parentIndex": '0' , 
         "childIndex": '3' , 
         "parent": "ROOT", 
         "child": "root3" 
       }, 
       { 
         "parentIndex": '3' , 
         "childIndex": '2' , 
         "parent": "root3" , 
         "child": "root2" 
       }, 
       { 
         "parentIndex": '3' , 
         "childIndex": '1' , 
         "parent": "root3" , 
         "child": "root1" 
       } 
       ]; 

我需要上面的JSON轉換爲使用遞歸樹結構中的Javascript。樹結構將類似於:

nodeStructure: { 
     text: { name: "root3" }, 
     children: [ 
      { 
       text: { name: "root2" } 
      }, 
      { 
       text: { name: "root1" } 
      } 
     ] 
    } 
}; 
+0

的數據排序?你有嘗試過什麼嗎? –

+0

數據不需要排序(排序不需要在輸出中)。這只是一個示例數據。 – Geeta

+0

你爲什麼需要遞歸? –

回答

0

使用下面的代碼:

var jsonObj = [ 
      { 
        "parentIndex": '0' , 
        "childIndex": '3' , 
        "parent": "ROOT", 
        "child": "root3" 
      }, 
      { 
        "parentIndex": '3' , 
        "childIndex": '2' , 
        "parent": "root3" , 
        "child": "root2" 
      }, 
      { 
        "parentIndex": '3' , 
        "childIndex": '1' , 
        "parent": "root3" , 
        "child": "root1" 
      } 
      ]; 

function filter(array,condition){ 
    var result = []; 
    for (var i = 0; i < array.length; i++) { 
    if(condition(array[i])){ 
     result.push(array[i]); 
    } 
    } 
    return result; 
} 


function getChilds(parentKey,items){ 
    var subItems = filter(items,function(n){return n.parent === parentKey}); 
    var result = []; 
    for (var i = 0; i < subItems.length; i++) { 
    var subItem = subItems[i]; 
    var resultItem = { 
     text: {name:subItem.child} 
    }; 
    var kids = getChilds(subItem.child , items); 
    if(kids.length){ 
     resultItem.children = kids; 
    } 
    result.push(resultItem); 
    } 
    return result; 
} 


var rootItems = getChilds('ROOT',jsonObj); 
+0

謝謝。這工作完美。 – Geeta

0

你可以使用一個循環的方法與收集所有節點和結果對象的臨時對象,至極返回節點這是根節點。

var data = [{ parentIndex: '0', childIndex: '3', parent: "ROOT", child: "root3" }, { parentIndex: '3', childIndex: '2', parent: "root3", child: "root2" }, { parentIndex: '3', childIndex: '1', parent: "root3", child: "root1" }], 
 
    tree = function (data, root) { 
 
     var r, o = {}; 
 
     data.forEach(function (a) { 
 
      o[a.childIndex] = { text: { name: a.child } }; 
 
      if (o[a.childIndex] && o[a.childIndex].children) { 
 
       o[a.childIndex].children = o[a.childIndex].children; 
 
      } 
 
      if (a.parentIndex === root) { 
 
       r = o[a.childIndex]; 
 
      } else { 
 
       o[a.parentIndex] = o[a.parentIndex] || {}; 
 
       o[a.parentIndex].children = o[a.parentIndex].children || []; 
 
       o[a.parentIndex].children.push(o[a.childIndex]); 
 
      } 
 
     }); 
 
     return r; 
 
    }(data, '0'); 
 

 
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }