0

我很难将键值(它们是数组)围绕在基于节点的/树形结构中。下面是一些示例代码来帮助解释。

我想把这个...

// key value data
var rawData = {
    "1": [],
    "2": [10],
    "3": [2,5,11],
    "4": [],
    "5": [1,7,6],
    "6": [4],
    "7": [],
    "8": [9],
    "9": [],
    "10": [],
    "11": []
}

到这个树形图...

// tree map
var treeData = {
    "id": "ALL",
    "contents": [
        {   
            "id": "3",
            "contents": [
                { 
                    "id": "2",
                    "contents": [
                        { "id": "10" }
                    ]
                }, { 
                    "id": "5",
                    "contents": [
                        { "id": "1" },
                        { "id": "7" },
                        { 
                            "id": "6",
                            "contents": [
                                { "id": "4" }
                            ]
                        }
                    ] 
                },
                { "id": "11" }
            ]
        },
        {   
            "id": "8",
            "contents": [
                { "id": "9" }
            ]
        }
    ]
}

我相信涉及某种形式的递归,但我很难遍历节点......

var traverse = function(rawData) {
    for (var i in rawData){
        var datum = rawData[i];

        for (var j in datum) {
            if(i===datum[j]){
                // tack on node to datum
            }
            traverse(rawData);
        }
    }
}   
4

1 回答 1

0

使用 for in 无法遍历数组 in,而是:

for (var j = 0; j < datum.length; i++) {
        if(i===datum[j]){
            // tack on node to datum
        }
        traverse(rawData);
    }
于 2013-01-22T06:19:17.837 回答