How to use ES6 Hash Map on any object without maintaing a reference (I.e. Java hashcode)

无人久伴 提交于 2019-12-11 02:32:38

问题


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


来源:https://stackoverflow.com/questions/28357647/how-to-use-es6-hash-map-on-any-object-without-maintaing-a-reference-i-e-java-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!