-3

Below is an array of objects which I need to print in the below expected format only using forEach in javascript

var donuts = [
    { type: "Dairy Milk", cost: 1.22 },//object
    { type: "Kit Kat", cost: 2.45 },
    { type: "Milky Bar", cost: 1.59 }
];

Expected output:

Dairy Milk cost $1.22 each
Kit Kat cost $2.45 each
Milky Bar cost $1.59 each

How do I do that?

YakovL
  • 7,557
  • 12
  • 62
  • 102

2 Answers2

0
donuts.forEach(d => console.log(`${d.type} cost $${d.cost} each`))

Every array in JavaScript has a method called forEach that basically calls a function for each of the elements of your array. Inside this function you can call console.log.

The example above uses the arrow function notation, which apart from a few differences is basically just a more concise way to declare a function.

Also in this example you can notice the use of string templates, denoted by the text inside backticks, where you can use placehoders ${} to place dynamic content in your string.

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Maximilian Peters Mar 25 '18 at 20:00
  • 1
    You are totally right @MaximilianPeters I have actually answered this question on the mobile app and will improve the answer as soon as I get home. – Renato Gama Mar 25 '18 at 20:01
0

You could do:

yourArray.forEach(function(element){
    console.log(element.type + ‘ costs $’ + element.cost + ‘ each’);
});
Renato Gama
  • 16,431
  • 12
  • 58
  • 92
Herman Neple
  • 156
  • 12