How to use forEach in vueJs?

I have a response like below from an API call,


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,

You can also use .map() as:

var list=[];, key) {

This is an example of forEach usage:

let arr = [];

this.myArray.forEach((value, 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) => {
    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:

In VueJS you can loop through an array like this :
const array1 = [‘a’, ‘b’, ‘c’];

Array.from(array1).forEach(element => 

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {

You can use native javascript function

var obj = {a:1,b:2};

    console.log(key, obj[el])

or create an object prototype foreach, but it usually causes issues with other frameworks

if (!Object.prototype.forEach) {
  Object.defineProperty(Object.prototype, 'forEach', {
    value: function (callback, thisArg) {
      if (this == null) {
        throw new TypeError('Not an object');
      thisArg = thisArg || window;
      for (var key in this) {
        if (this.hasOwnProperty(key)) {
, this[key], key, this);

var obj = {a:1,b:2};

obj.forEach(function(key, value){
    console.log(key, value)

The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.

Native Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

Underscore Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts