0

Is there any restriction on the key type of a Map data structure. Seems like it handles primitive data types like string and number without problem. but it can't somehow locate a key when it's of type of object. I checked it in the REPL and it confirms my assumption. But why it is not mentioned anywhere?

$ node
Welcome to Node.js v12.8.0.
Type ".help" for more information.
> const a = new Map();
undefined
> a.set({a: 1, b: 2}, 3);
Map { { a: 1, b: 2 } => 3 }
> a.get({a: 1, b: 2});
undefined
> const b = new Map();
undefined
> b.set('str', 3);
Map { 'str' => 3 }
> b.get('str');
3
>
pouya
  • 3,400
  • 6
  • 38
  • 53
  • 1
    You created two separate objects (though, containing the same key-value pairs), so a Map (and Set) will consider them to be different. `map.set(key1, val)` will result in `map.get(key2)` returning `val` only if `key1 === key2` – CertainPerformance Aug 10 '19 at 11:04
  • @CertainPerformance so Map is suited for primitve data types? then why in [Mozilla knowledge base](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) Objects are also mentioned as a Map key. What if we want objects to be used as a map key? – pouya Aug 10 '19 at 11:10
  • 2
    Maps work just fine with objects, but if you want to retrieve a value set with an object key, you need to pass that same object into it. eg `const obj = { a: 1, b: 2 }` and then setting and getting with `obj` would work just fine. Your code is creating two entirely separate objects - they're not `===`, so it doesn't work – CertainPerformance Aug 10 '19 at 11:11

0 Answers0