Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use forEach in vueJs?

I have a response like below from an API call,

response

Now, I have to repeat the whole arrays inside the arrays. How do I do that in VueJS?

I have searched for using forEach.. nowhere I found forEach usage like key|value pair.

Can anyone help me on how to fetch the values from that arrays by using either forEach or any else(VueJS)?

Thanks & Regards,

like image 689
Jaccs Avatar asked Mar 01 '17 15:03

Jaccs


2 Answers

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });
like image 99
Arun D Avatar answered Oct 24 '22 19:10

Arun D


This is an example of forEach usage:

let arr = [];

this.myArray.forEach((value, index) => {
    arr.push(value);
    console.log(value);
    console.log(index);
});

In this case, "myArray" is an array on my data.

You can also loop through an array using filter, but this one should be used if you want to get a new list with filtered elements of your array.

Something like this:

const newArray = this.myArray.filter((value, index) => {
    console.log(value);
    console.log(index);
    if (value > 5) return true;
});

and the same can be written as:

const newArray = this.myArray.filter((value, index) => value > 5);

Both filter and forEach are javascript methods and will work just fine with VueJs. Also, it might be interesting taking a look at this:

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

like image 25
Carolyne Stopa Avatar answered Oct 24 '22 19:10

Carolyne Stopa