How to use ES6 Hash Map on any object without main

2019-07-20 14:32发布

问题:

I've been experimenting with ES6 Map in io.js and realized that I can't do the following:

var map = new Map()
map.set( {key:"value"}, "some string");
map.get( {key:"value"} ); // undefined. I want "some string"

This is because {key:"value"} === {key:"value"} is false.

I need to be able to use an object as a key but not require the ACTUAL object to lookup the value like how java HashMap uses hashcode and equals. Is this possible?

回答1:

  • If the lack of object identity stems from a serialize-deserialize roundtrip just give them a unique ID that survives that and use that ID as key
  • calculate a key from a subset of its properties if you can be certain that the remaining properties either depend on that subset or are irrelevant to your operation
  • implement your own hash map and object hashing. this can get tricky with host objects but should be fairly simple with JSON-compatible data
  • JSON-encode before each get or set. It's quite inefficient and only works with JSON-serializeable objects. But easier to implement than the previous option