6

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?

2
  • Why don't use JSON.parse({key:"value"}) as your key? Commented Feb 6, 2015 at 4:04
  • If you are prepared to go all-in with Immutable.js, you can use Record as complex key for immutable Map. immutable-js.github.io/immutable-js Commented Oct 25, 2020 at 19:53

1 Answer 1

8
  • 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.