How to make a foreach in JavaScript? [duplicate]

1

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 fetch each campaign from within the campanhas array?

The array return of an array follows:

this.campanhas{campanha1{},campanha2{} ,campanha3{}}
    
asked by anonymous 28.12.2017 / 22:08

2 answers

0

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

Example to get valor1 of each sub-array in 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);
}
    
28.12.2017 / 23:35
0

I can suggest you use the native forEach of ECMAScript, but if you wanted to support old 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 on MDN documentation

    
29.12.2017 / 14:46