How to make a foreach in Javascript?

Asked

Viewed 1,157 times

1

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

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

Below is the return array of an array:

this.campanhas{campanha1{},campanha2{} ,campanha3{}}
  • This question already has answers on: https://answall.com/questions/2506/foreach-em-javascript

  • 1

    foreach is more like for...of than for...in, as they usually associate.

2 answers

0


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

Example to catch the 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);
}

  • dvd , I had done exactly like this and for some reason , could not pass the value

  • After I realized that my problem wasn’t with the for itself , but with the return of the campaigns array, this resolution worked perfectly

0

May I suggest using Ecmascript’s native foreach, but if you wanted to support older browsers, simply 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.