如何遍历js对象并记录遍历路径?

时间:2014-03-04 06:07:04

标签: javascript algorithm

对象的遍历很容易,但我发现很难找出自己的遍历路径。

例如,这里我们有如下数据:

data = {
    a: 'A',
    b: {
        d: [
            'F',
            'G'
        ],
        e: 'D'
    },
    c: 'C'
}

我想输出这样的遍历路径:

['a']
['b', 'd', 0]
['b', 'd', 1]
['b', 'e']
['c']

如何编写算法?

1 个答案:

答案 0 :(得分:2)

function rec(currentObject, path) {
    if (typeof currentObject !== "string" && currentObject.length) {
        for (var i = 0; i < currentObject.length; i += 1) {
            rec(currentObject[i], path.concat(i));
        }
    } else if (typeof currentObject === "object") {
        for (var item in currentObject) {
            rec(currentObject[item], path.concat(item))
        }
    } else {
        console.log(path);
    }
}

rec(data, []);

<强>输出

[ 'a' ]
[ 'b', 'd', 0 ]
[ 'b', 'd', 1 ]
[ 'b', 'e' ]
[ 'c' ]