0

I have a Javascript map that I need to loop through, however the value of the map is an object which is an array. This is what I have so far;

Javascript to loop through map

var food = 'pizza'
var ten = 10

function logMapElements(value, key, map) {
  console.log(`${key} = ${value}`);
}

new Map([['foo', 3], ['bar', {item:food, price:ten}]])
  .forEach(logMapElements);

Actual Output;

> "foo = 3"
> "bar = [object Object]"

What I expected Output to look like;

> "foo = 3"
> "bar = [{item:pizza, price:10]"

What am I doing incorrectly that it does not show the actual object variables?

Thanks for any help!

Bell
  • 45
  • 9
  • 2
    Use `JSON.stringify(value)` or log them separately: `console.log(key, "=", value)` – adiga Jan 25 '20 at 14:46
  • @adiga Thanks, Good answer. However I need the object to stay as a variable, so that I can use the "item" and "price" in operations after the loop. Any ideas? – Bell Jan 25 '20 at 14:50
  • `JSON.stringify()` will not mutate the object. `value` is still an object. When you use it in a string context, it calls the `toString()` method which returns `[object Object]`. If you don't use the value within a template literal, like `console.log(key, "=", value)`, you don't even have to use `JSON.stringify()` – adiga Jan 25 '20 at 14:52

0 Answers0