admin管理员组文章数量:1178539
I have some data that is in JSON object array. I'm trying to use nested forEach loops to extract the data.
The data is modeled like belo. There's multiple dataModels and multiple childNodes inside the dataModels.
//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?
I have some data that is in JSON object array. I'm trying to use nested forEach loops to extract the data.
The data is modeled like belo. There's multiple dataModels and multiple childNodes inside the dataModels.
//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?
Share Improve this question edited May 11, 2015 at 20:03 user1142130 asked May 11, 2015 at 20:00 user1142130user1142130 1,6453 gold badges20 silver badges36 bronze badges 1 |3 Answers
Reset to default 15You are not targeting the array inside the entry
object, you need to loop over the childNodes
property in order to get the data you want. See example below.
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);
});
});
JsFiddle demo
Nesting foreach is really a bad practice. Instead of that you can use the map() function to get data.
Suppose a array of object be like this & now here how to use map instead of multiple foreach();
data = [{
dataModels: [{
childNodes: {
appId: 'foo'
}
}]
}];
data.forEach(function(obj) {
var res = obj.dataModels.map(function(o) {
return o.childNodes;
});
console.log(res[0]);
});
It appears to me that your solution is correct, but you're missing a parentheses and you're not referencing the childNodes attribute:
data.forEach(function(entry){
entry.childNodes.forEach(function(childrenEntry){
console.log(childrenEntry.appId);
})
})
本文标签: javascriptNested forEach loop does not workStack Overflow
版权声明:本文标题:javascript - Nested forEach loop does not work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738049394a2055192.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
entry.childNodes.forEach
maybe? And you have a typo infunction(childrenEntry{
– DontVoteMeDown Commented May 11, 2015 at 20:01