Home > front end >  forEach() method in Javascript for key-value pairs
forEach() method in Javascript for key-value pairs

Time:03-10

How to print only the value(s) in the display?

let room1 = new Map();
room1.set("candles", 8)
room1.set("fridge", 1)
room1.set("washing machine", 3)
room1.set("chairs", 4)
room1.set("sofa", 2)
room1.set("jacuzzi", 6)

let text4 = "";
room1.forEach(function(key) {
  text4  = key   "<br>"
});

document.getElementById("demo8").innerHTML = text4;
<p id="demo8"></p>

CodePudding user response:

You could get only the keys directly.

let rooms = new Map();
rooms.set("candles", 8)
rooms.set("fridge", 1)
rooms.set("washing machine", 3)
rooms.set("chairs", 4)
rooms.set("sofa", 2)
rooms.set("jacuzzi", 6)

console.log([...rooms.keys()]);

CodePudding user response:

Follow these steps:

  1. Add the second parameter value to forEach function

  2. Change in text4 to concat the value and not key:


Adjustments:

room1.forEach(function(key, value) {
  text4  = value   "<br>"
});

Example:

let room1 = new Map();
room1.set("candles", 8)
room1.set("fridge", 1)
room1.set("washing machine", 3)
room1.set("chairs", 4)
room1.set("sofa", 2)
room1.set("jacuzzi", 6)

let text4 = "";
room1.forEach(function(key, value) {
  text4  = value   "<br>"
});

document.getElementById("demo8").innerHTML = text4;
<p id="demo8"></p>

Reference:

  • Related