Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested forEach loop does not work

Tags:

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?

like image 857
user1142130 Avatar asked May 11 '15 20:05

user1142130


People also ask

Why is my foreach not working?

The "forEach is not a function" error occurs when we call the forEach() method on a value that is not of type array, Map , or Set . To solve the error, make sure to only call the forEach method on arrays, Map or Set objects. Copied!

Can foreach loops be nested?

An important feature of foreach is the %:% operator. I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects.

Can we use for loop inside foreach loop?

Nested for LoopsWe can also use a for loop inside another for loop.

Are nested foreach loops bad?

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.


2 Answers

You 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

like image 62
GillesC Avatar answered Oct 06 '22 08:10

GillesC


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]);
});
like image 23
Pranav Naxane Avatar answered Oct 06 '22 09:10

Pranav Naxane