0

Why does this map print empty? I'd expect it to be populated from the array? I'm probably missing something small.

let numbers = [1, 2, 3];

let numberMap = numbers.reduce((map, obj) => {
  return map.set(obj, obj + 1);
}, new Map());

console.log(JSON.stringify(numberMap));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Thomas
  • 368
  • 1
  • 7
  • 19
  • 3
    **It isn't**, but it looks that way when you log it because `Map` objects don't store their elements as object properties. `JSON.stringify` only includes own, enumerable properties, but `Map` entries aren't properties, so it looks empty. Instead: `console.log(JSON.stringify([...numberMap.entries()]))`. – T.J. Crowder Feb 02 '22 at 17:45
  • There's an original question on here about this, I'll see if I can find it. – T.J. Crowder Feb 02 '22 at 17:45
  • @T.J. Crowder Could it be [this](https://stackoverflow.com/questions/50153172/how-to-serialize-a-map-in-javascript) one? – David Fontes Feb 02 '22 at 17:46
  • 1
    @DavidFontes - Good find. I've added it to the list. :-) – T.J. Crowder Feb 02 '22 at 17:47
  • JSON can only represent a subset of what a JS value can contain. The default representation of `console.log` is a lot better for that. If you'd drop the `JSON.stringify`, you'd see the elements in the output. – CherryDT Feb 02 '22 at 17:54
  • 1
    @CherryDT - Indeed. Although then you do have to worry about the [whole deferred evaluation thing](http://stackoverflow.com/questions/38660832/element-children-has-elements-but-returns-empty-htmlcollection). :-D *(But it can be useful, too.)* – T.J. Crowder Feb 02 '22 at 17:56

0 Answers0