Nested forEach loop not working

I have some data that is in an array of JSON objects. I am trying to use nested forEach loops to retrieve data.

The data is modeled as white. Inside dataModels, there are several dataModels and several childNodes.

//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);
    })
})

      

However, the above does not work and it gives me an error saying "write" is not a function. Is there a better way to achieve what I am trying to do?

+3


source to share


3 answers


You are not targeting an array within an object entry

, you need to loop over the property childNodes

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

+2


source


Nesting foreach is really bad practice. Instead, you can use the map () function to get the data.

Suppose the object array will be like this and now here's how to use a 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]);
});
      

Run codeHide result


+2


source


It seems to me that your solution is correct, but you are missing parentheses and are not referencing the childNodes attribute:

data.forEach(function(entry){
    entry.childNodes.forEach(function(childrenEntry){
      console.log(childrenEntry.appId);
    })
})

      

0


source







All Articles