对象的遍历很容易,但我发现很难找出自己的遍历路径。
例如,这里我们有如下数据:
data = {
a: 'A',
b: {
d: [
'F',
'G'
],
e: 'D'
},
c: 'C'
}
我想输出这样的遍历路径:
['a']
['b', 'd', 0]
['b', 'd', 1]
['b', 'e']
['c']
如何编写算法?
答案 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' ]