Javascript 如何编写一个函数,根据多维对象中的嵌套数自动为…创建循环?
这是我要生成的函数的伪代码中的过程版本。如果我编辑列表对象以包含更多属性或甚至更多嵌套对象,如何创建递归函数,在对象.hasOwnProperty出现时进行自我检测,从而在循环中为…创建更多,而不考虑嵌套对象属性的名称Javascript 如何编写一个函数,根据多维对象中的嵌套数自动为…创建循环?,javascript,Javascript,这是我要生成的函数的伪代码中的过程版本。如果我编辑列表对象以包含更多属性或甚至更多嵌套对象,如何创建递归函数,在对象.hasOwnProperty出现时进行自我检测,从而在循环中为…创建更多,而不考虑嵌套对象属性的名称 function hierarchy() { list = { "cat": { "color": "red", "family": { "mother": "jesu
function hierarchy() {
list = {
"cat": {
"color": "red",
"family": {
"mother": "jesus",
"father": "mary"
}
},
"dog": {
"color": "blue",
"family": {
"mother": "harold"
}
},
"bird": {
"color": "orange"
},
"pokemon": {
"color": "green",
"family": {
"mother": "fdajs",
"brothers": {
1: "james",
2: "what"
}
}
}
};
for (levelOne in list) {
for (levelTwo in list[levelOne]) {
if (levelTwo === "color") {
console.log(levelTwo+" "+list[levelOne][levelTwo]);
}
if (levelTwo === "family") {
for (levelThree in list[levelOne][levelTwo]) {
console.log(levelTwo+" "+"("+levelThree+") "+list[levelOne][levelTwo[levelThree]);
}
}
if (//if properties and objects are added to list they should be automatically detected here) {
for (this.level in this.parent.level) {
console.log(list[firstChild][this.level]
}
}
for (this.level in list[firstChild][secondChild]) {
for (etc...) {
for (etc...) {
}
}
}
}
}
}
也许是类似于这个伪代码?可能有一些我不熟悉的方法可以将父对象和子对象作为数组获取。这是一个典型的递归问题:
function createNewLevel() {
for (this.level in myObject) {
if (this.object.hasOwnProperty(//list child properties and objects) {
//for every property, do something
//for every nested object, instantiate new createNewLevel(this.level)
}
}
}
非常感谢你的帮助@如果这对你有帮助的话,请你也投赞成票,谢谢。
var path = [];
function f(obj) {
var k;
for (k in obj) {
path.push(k);
if (!(typeof obj[k] === 'object')) {
console.log(path.join('.') + ': ' + obj[k]);
} else {
f(obj[k]);
}
path.pop();
}
}
f(list);