在Javascript中循环遍历三重嵌套对象 [英] Looping through a triple nested object in Javascript
问题描述
我已经声明了一个三重嵌套对象,如下所示:
I have declared a triple nested object, like so:
var food = {
"fruit": {
"apples": {
"redApples": 20,
"greenApples": 30
},
"bananas": {
"yellowBananas": 10
}
},
"grains": {
"bread": {
"brownBread": 50
}
}
};
我发现这个问题,它用于迭代对象的对象,但是我被卡住了。我将如何遍历此对象?
I found this question, which worked for iterating through an object of an object, but I'm stuck. How would I iterate through this object?
更新:对于此特定问题,嵌套的for循环可以正常工作,如下所示:
Update: For this specific problem, nested for-loops would work fine, like this:
for(var key in food)
for(var prop in food[key])
for(var foo in food[key][prop])
console.log(food[key][prop][foo]);
但是,下面有一些很好的递归函数可以为无限期嵌套的对象执行此操作。
However, there are some good recursive functions below which would do this for indefinitely nested objects.
推荐答案
Martin是对的,递归函数就是这种方法。你的函数应该检查对象的属性。如果是 - 函数必须通过调用自身来更深入,但是使用嵌套对象。
Martin is right, recursive function is the approach. Your function should check is the attribute an object. If it is - function must walk deeper by calling itself also, but with a nested object.
function recursiveIter(obj){
for (var i in obj){
if (typeof obj[i]=="object"){
recursiveIter(obj[i]);
}
else {
$('.ins').append(obj[i]); // or what do you want to do with that
}
}
}
recursiveIter(food);
jsfiddle 采用这种方法。
这篇关于在Javascript中循环遍历三重嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!