Javascript 嵌套的 forEach 循环不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30176604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested forEach loop does not work
提问by user1142130
I have some data that is in JSON object array. I'm trying to use nested forEach loops to extract the data.
我有一些 JSON 对象数组中的数据。我正在尝试使用嵌套的 forEach 循环来提取数据。
The data is modeled like belo. There's multiple dataModels and multiple childNodes inside the dataModels.
数据像 belo 一样建模。数据模型中有多个数据模型和多个子节点。
//this is what an example data looks like
dataModels[0].childNodes[0].appId
I am trying to do something like the following:
我正在尝试执行以下操作:
dataModels.forEach(function(entry){
entry.forEach(function(childrenEntry){
console.log(childrenEntry.appId);
})
})
The above however does not work and it gives me an error saying that 'entry' is not a function. Is there a better way to achieve what I'm trying to do?
然而,上面的方法不起作用,它给了我一个错误,说“条目”不是一个函数。有没有更好的方法来实现我想要做的事情?
采纳答案by GillesC
You are not targeting the array inside the entryobject, you need to loop over the childNodesproperty in order to get the data you want. See example below.
您不是针对entry对象内的数组,您需要遍历该childNodes属性以获得所需的数据。请参阅下面的示例。
var dataModels = [];
dataModels[0] = {
childNodes: []
};
dataModels[0].childNodes[0] = {
appId: "foo"
};
dataModels.forEach(function(entry){
entry.childNodes.forEach(function(childrenEntry) { // was missing a )
console.log(childrenEntry.appId);
});
});
回答by Pranav Naxane
Nesting foreach is really a bad practice. Instead of that you can use the map() function to get data.
嵌套 foreach 确实是一种不好的做法。取而代之的是,您可以使用 map() 函数来获取数据。
Suppose a array of object be like this & now here how to use map instead of multiple foreach();
假设一个对象数组是这样的 & 现在这里如何使用 map 而不是多个 foreach();
data = [{
dataModels: [{
childNodes: {
appId: 'foo'
}
}]
}];
data.forEach(function(obj) {
var res = obj.dataModels.map(function(o) {
return o.childNodes;
});
console.log(res[0]);
});
回答by Craig Kelly
It appears to me that your solution is correct, but you're missing a parentheses and you're not referencing the childNodes attribute:
在我看来,您的解决方案是正确的,但是您缺少括号并且您没有引用 childNodes 属性:
data.forEach(function(entry){
entry.childNodes.forEach(function(childrenEntry){
console.log(childrenEntry.appId);
})
})

