从json获取分层数据

时间:2014-05-15 08:11:55

标签: javascript json algorithm

var oTeamHierarchyJson = [
            {
                "Key": "10011",
                "Name": "A",                
                "Job Title": "VP",                
                "children": "C",
                "Parent": "1000",
                "Level": "1"
            },
            {
                "Key": "10012",
                "Name": "B",                
                "Job Title": "VP",                
                "children": "D",
                "Parent": "1001",
                "Level": "1"
            },
            {
                "Key": "10013",
                "Name": "C",               
                "Job Title": "GM",                
                "children": "E",
                "Parent": "10011",
                "Level": "2"
            },
            {
                "Key": "10014",
                "Name": "D",
                "Job Title": "MP",                
                "children": "F",
                "Parent": "10013",
                "Level": "3"
            }
        ];

我想编写一个函数,它将获取一个键并递归地获取它的所有子项。

function filterJSONData(currentKey) {
      //return all children recursively
}

表示10011 - 返回10013,10014

3 个答案:

答案 0 :(得分:3)

function getKeys(key) {
    var keys = [];
    # We all the keys for which the parent is key passed in as argument
    oTeamHierarchyJson.forEach(function(currentItem) {
        if (currentItem.Parent === key) {
            keys.push(currentItem.Key);
        }
    });

    # For eavery matched key, call getKeys recursively and flatten the result
    return [].concat.apply([key], keys.map(getKeys));
}

console.log(getKeys("10011"));
# [ '10011', '10013', '10014' ]

答案 1 :(得分:1)

数据结构只保存父关系,而不保存子关系,这种关系不适合遍历。有两种方法可以避免这个缺点:

  1. 处理数组以使每个音符引用其所有子节目
  2. 介绍一个返回节点所有子节点的辅助函数
  3. 之后,以递归方式查找给定节点的所有后继者要容易得多。

答案 2 :(得分:1)

您可以从平面数据列表中构建树。下面的代码递归地添加了一个属性子项,并用每个节点的子项填充它。 见http://jsfiddle.net/jeromerg/234jk/

buildTree = function(array, nodeKey) {

    // getNode
    var node = null;
    for(var i=0; i<array.length; i++) {
        if(array[i].Key == nodeKey) {
             node = array[i];
            break;
        }
    }

    if(node === null) {
        null;   
    }

    // fill new children property
    node.childen = [];
    for(var i=0; i<array.length; i++) {
        if(array[i].Parent == nodeKey) {
            alert("COUCOU");
            node.childen.push(array[i]);

            // recursive call!
            buildTree(array, array[i].Key);
        }
    }

    return node;

}

var result = buildTree(oTeamHierarchyJson, 10011);

alert(JSON.stringify(result));