遍历对象并构建树谱系

时间:2015-06-25 19:50:33

标签: javascript iteration tree-traversal

Json对象:

var json = {
    "Tree": [{
        "Title": "Condition",
        "Attr": {
            "Id": 2258,
            "Zone": null
        },
        "Children": [{
            "Title": "General Wellness",
            "Attr": {
                "Id": 2315,
                "Zone": null
            },
            "Children": [{
                "Title": "Family Health",
                "Attr": {
                    "Id": 2262,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Healthy Home",
                "Attr": {
                    "Id": 2316,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Vitamins",
                "Attr": {
                    "Id": 2317,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Recipes",
                "Attr": {
                    "Id": 2318,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Caregiving",
                "Attr": {
                    "Id": 2325,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Healthy Eating",
                "Attr": {
                    "Id": 2346,
                    "Zone": null
                },
                "Children": []
            }, {
                "Title": "Travel Health",
                "Attr": {
                    "Id": 2347,
                    "Zone": null
                },
                "Children": []
            }]
        }]
    }]
}

我能够遍历树但是我无法构建树结构,例如,如果我想查找“食谱”它应该返回结果为:

条件>一般健康>配方

更新:

通过以下方式完成遍历:

function process(key,value) {
    alert(key + " : "+value);
}

function traverse(o,func) {
    for (var i in o) {
        func.apply(this,[i,o[i]]);  
        if (o[i] !== null && typeof(o[i])=="object") {            
            traverse(o[i],func);
        }
    }
}

traverse(json,process);

0 个答案:

没有答案