How to make a foreach in JavaScript? [duplicate]

this question already has answers here : "foreach" in JavaScript (6 responses) Closed 3 years ago years .

My application returns an array of array, where campanhas[] is an array of campanha[] which is also an array.

How can I make a foreach to grab each campaign from within the campanhas array?

Follows below the return array of an array:

this.campanhas{campanha1{},campanha2{} ,campanha3{}}
Author: Sam, 2017-12-28

2 answers

You can make a loop Type for(valor in array) that will take the value you want.

Example to take the valor1 of each sub-array at campanhas:

var campanhas = {
   campanha1: {
      valor1: "a",
      valor2: "b"
   },
   campanha2: {
      valor1: "c",
      valor2: "d"
   },
   campanha3: {
      valor1: "e",
      valor2: "f"
   }
};

for(valor in campanhas){
   console.log(campanhas[valor].valor1);
}
 0
Author: Sam, 2017-12-28 22:35:50

I can suggest using ECMAScript's native forEach, but if you want to support older browsers, just include a simple polyfill in your application:

if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  };
}

And use as follows:

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

More information in MDN documentation

 0
Author: Vinicius Dutra, 2017-12-29 13:46:35