i’m currently working with vanilla javascript, my problem looks like this:
I’m iterating through an object array with json format and for some reason when i try to execute a for loop inside the forEach it won’t display as i want. What I have in the objectArray is a set of people with some rating, what I want to achieve is adding an image (Which will display the amount of stars) using the for loop, however it won’t execute anything inside the for loop.
I post my code below:
const CONTAINER = document.getElementById('starsContainer'); // Container where the stars will go
// Object Array with sets of data
const ObjectArray = [{
name: 'Oscar',
age: 20,
rating: 5
},
{
name: 'Marcelo',
age: 24,
rating: 4
},
{
name: 'John',
age: 30,
rating: 3
}];
// Displaying the object array
console.log(ObjectArray);
// Iterating through the object array
ObjectArray.forEach(object => {
// Displays the rating of the current object
console.log(object.rating);
// Should add an image based on the amount of rating
for(let i = object.rating; i <= 0; i--){
// It won't display nothing inside the for loop
console.log(object.rating);
// Should add an image
CONTAINER.innerHTML += `<img src="stars.png">`;
}
});
I’ve tried creating a function with the for loop inside it and calling it from the forEach without success:
function myFunction(){
// Object Array with sets of data
const ObjectArray = [{
name: 'Oscar',
age: 20,
rating: 5
},
{
name: 'Marcelo',
age: 24,
rating: 4
},
{
name: 'John',
age: 30,
rating: 3
}];
ObjectArray.forEach(object => {
console.log(object.rating);
calculateStars(object.rating, 'starsContainer');
});
}
function calculateStars(rating, starsContainer) {
const CONTAINER = document.getElementById(starsContainer);
for (let i = rating; i <= 0; i--) {
CONTAINER .innerHTML += `
<img src="stars.png">
`;
}
}
PD: I know all the stars will be added to the same container regardless of the current person/object, it doesn’t matter.
pagetableK is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.