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,
This question is related to
javascript
arrays
foreach
vuejs2
vue.js
In VueJS you can use forEach like below.
let list=[];
$.each(response.data.message, function(key, value) {
list.push(key);
});
So, now you can have all arrays into list . use for loop to get values or keys
You can use native javascript function
var obj = {a:1,b:2};
Object.keys(obj).forEach(function(key){
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)) {
callback.call(thisArg, 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);
In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];
Array.from(array1).forEach(element =>
console.log(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)) {
this.media.images.push(file)
console.log(this.media.images)
}
}
You can also use .map() as:
var list=[];
response.data.message.map(function(value, key) {
list.push(value);
});
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
Source: Stackoverflow.com