Question:
I have an array that has information that I need to print in a html, in a javascript file I am trying to obtain the values of the array through a forEach, below the detail:
static get properties() {
return {
_element: {
type: Object,
notify: true,
value: function () {
return {};
}
},
books: {
type: Array,
value: [],
notify: true
}
}
};
dataLoaded(element) {
this.set('_element', element);
let filter = [];
this.set('books', []);
element.data.forEach(item => {
filter.push({
'id': item.id
})
});
this.set('books', filter);
}
Answer:
In JavaScript forEach()
is a function of an iterable , it can be a Map
, Set
or an Array
to name a few, so first you must make sure that the variable that you are applying that function is an iterable
If your variable is, let's say, an object, the forEach()
function will not be available, I give you an example
const anObject = {
name: "Carlos",
lastname: "Proaño",
city: "Mérida"
};
anObject.forEach(item => console.log(item));
It is not the same with an arrangement
const anArray = [
'peras',
'manzanas',
'naranjas',
'uvas',
];
anArray.forEach(item => console.log(item));
If you are trying to apply the forEach()
to an object you must first convert it to an array if IE support is not mandatory or you have a transpiler like Babel you can use Object.values()
, on the other hand if you don't have a transpiler and you need to support IE you can use a for...in
, I will put the example of the adapted documentation to show the functionality of the Object.values()
let string1 = "";
let string2 = "";
const object1 = {a: 1, b: 2, c: 3};
for (let property1 in object1) {
string1 += object1[property1];
}
Object.values(object1).forEach(item => {string2 += item});
console.log(string1);
console.log(string2);
Finally, if you need to return an array as a result of the iteration, I would recommend using Array.map()
const fruits = [
{id: 1, value: 'peras'},
{id: 2, value: 'naranjas'},
{id: 3, value: 'manzanas'},
{id: 4, value: 'uvas'},
];
const newArray = fruits.map(item => item.id);
console.log(newArray);