Skip to content
Advertisement

How to use forEach method for objects in array in JavaScript?

Here is an array of donut objects.

var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];

Directions: Use the forEach() method to loop over the array and print out the following donut summaries using console.log.

Jelly donuts cost $1.22 each
Chocolate donuts cost $2.45 each
Cider donuts cost $1.59 each
Boston Cream donuts cost $5.99 each

I wrote this code but it doesn’t work :

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

What’s wrong?

Advertisement

Answer

Instead of

donuts.forEach(function(donut) {

    console.log(donuts.type + " donuts cost $" + donuts.cost + " each");

});

change it to

donuts.forEach(function(donut) {

    console.log(donut.type + " donut cost $" + donut.cost + " each");

});

You are looping through the donuts array and calling each object a donut, but in your code, you are still trying to reference donuts.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement