让我们说我有一个(乱七八糟的)多维对象:
tree = {
"Russia": "vodka",
"Ireland": "potatos",
"France": {
"population": "a lot",
"states": {
"south": "alabama",
"north": "alaska"
},
"founding": 1776
},
"USA": {
"population": {
"hispanic": {
"origin": "spain",
"food": "tacos"
},
"chinese": {
"origin": "UK",
"food": "eggroll"
}
},
"states": {
"big": "lyon",
"small": "paris"
},
"founding": 1000
},
"UK": {
"population": 444343,
"states": {
"wht": "brick",
"fine": "rock",
"sta": "wine"
},
"founding": {
"first conquer": {
"vikings": 102,
"nords": 456,
"irish": 1000,
"french": "everyday"
}
}
}
}
我一直试图弄清楚如何遍历树,这样我就可以控制每个"等级" (如果有一个标准术语,请告诉我!),例如键和#34;俄罗斯," "爱尔兰," "法国," " USA,"和"英国"将是第一级。人口,州和建国将是二级等。像这样......
function treeLevels(object) {
function onlyExecuteOnFirstLevel() {
//some stuff
}
function recursion(object) {
for (k in object) {
//this isn't the kind of base case I need
if (!typeof object[k] == 'object') {
onlyExecuteonFirstLevel(); //this will run but also on undesired parts of the tree
} else {
recursion(object[k]);
}
}
}
}
阅读一些关于基本递归模式的帖子后,最好的解决方案似乎是在数组中创建数组?
treeLevelsKey = [];
treeLevelsValue = [];
function onlyExecuteOnFirstLevel(level) {
if (level == 0) {
//stuff
}
}
function treeLevels(object) {
for (k in object) {
treeLevelsKey[k] = [];
treeLevelsValue[object[k]] = [];
onlyExecuteOnFirstLevel(???) //the argument should be the first index of the desired array...but not sure
//base case
//recursion
}
}
我认为递归创建数组是正确的方法,但我无法弄清楚如何获取函数的参数来获取代码放入父数组的内容。
答案 0 :(得分:0)
以下是代码:
tree = {
"Russia": "vodka",
"Ireland": "potatos",
"France": {
"population": "a lot",
"states": {
"south": "alabama",
"north": "alaska"
},
"founding": 1776
},
"USA": {
"population": {
"hispanic": {
"origin": "spain",
"food": "tacos"
},
"chinese": {
"origin": "UK",
"food": "eggroll"
}
},
"states": {
"big": "lyon",
"small": "paris"
},
"founding": 1000
},
"UK": {
"population": 444343,
"states": {
"wht": "brick",
"fine": "rock",
"sta": "wine"
},
"founding": {
"first conquer": {
"vikings": 102,
"nords": 456,
"irish": 1000,
"french": "everyday"
}
}
}
};
function get_value(tree, key, level) {
if( typeof( tree[key] ) == "object" &&
Object.keys(tree).length >= 1 ) {
value = tree[ key ];
console.log(level + ":\t" + key );
for( k in value ) {
console.log((level + 1) + ":\t" + k );
get_value( tree[key], k, level + 1);
}
} else {
var hash = tree[ key ];
console.log(level + ":\t" + key );
}
}
for( key in tree ) {
var level = 0;
get_value( tree, key, level);
}