我有一个json,就像这样
{
"a": {
"b1": "blah blah",
"b2": "ahsbefbasef",
"b3": "adsfad af"
},
"c": {
"d1":"asef",
"d2":"fefef",
"d3":"ffgfgf"
}
}
现在我想遍历这个json并获得所有节点 - 深度明智,因为我想在一个数组中存储深度为0(a,c)的节点,深度为1的节点(c1,c2,c3, d1,d2,d3)在另一个数组中,依此类推,基本上打破json对象,并以单独的数组存储每个深度的节点
答案 0 :(得分:4)
您可以通过为每个嵌套对象使用递增级别来采用递归方法。然后取结果的级别并添加相同级别的键。
function iter(object, level) {
var keys = Object.keys(object);
level = level || 0;
result[level] = result[level] || [];
Array.prototype.push.apply(result[level], keys);
keys.forEach(function (key) {
if (object[key] && typeof object[key] === 'object') {
iter(object[key], level + 1);
}
});
}
var object = { a: { b1: "blah blah", b2: "ahsbefbasef", b3: "adsfad af" }, c: { d1: "asef", d2: "fefef", d3: "ffgfgf" } },
result = [];
iter(object);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以使用以下代码来满足您的要求。 在ECMAScript2015(a.k.a。ES6)中,您可以使用spread operator一次附加多个项目:
我已经对我的代码here 进行了基准测试,您可以检查下面的代码是否比接受的答案更快。
var obj = {
"a": {
"b1": "blah blah",
"b2": "ahsbefbasef",
"b3": "adsfad af"
},
"c": {
"d1": "asef",
"d2": "fefef",
"d3": "ffgfgf"
}
}
var response = {};
recursive(obj, 0, response);
console.log("result:",response);
function recursive(passedObject, depth, response) {
var keys = Object.keys(passedObject);
response[depth] = response[depth] || [];
response[depth].push(...keys);
keys.forEach(function(key){
if (passedObject[key] && typeof passedObject[key] === 'object') {
recursive(passedObject[key], depth + 1, response)
}
})
}

<强> 输出: 强>
result:
{
0 : ["a", "c"]
1 : ["b1", "b2", "b3", "d1", "d2", "d3"]
}
此处的基准测试结果: