如何在任何对象上使用ES6哈希映射,而不需要引用(即Java哈希码) [英] How to use ES6 Hash Map on any object without maintaing a reference (I.e. Java hashcode)

查看:150
本文介绍了如何在任何对象上使用ES6哈希映射,而不需要引用(即Java哈希码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在io.js中尝试使用ES6 Map,并意识到我无法执行以下操作:

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"

这是因为{key:value} === {key :value}是false。

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

我需要能够使用一个对象作为关键字,但不需要ACTUAL对象来查找值,就像Java HashMap使用的方式哈希码和等于。这是可能的吗?

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?

推荐答案


  • 如果缺少对象标识来源于序列化反序列化往返给他们一个唯一的ID,幸存下来,并使用该ID作为键

  • 从其属性子集中计算一个键,如果您可以确定剩余属性取决于该子集或与您的操作无关

  • 实现自己的散列图和对象散列。这可能会使主机对象变得棘手,但应该是相当简单的JSON兼容数据

  • JSON获取或设置之前的JSON编码。这是非常低效的,只适用于JSON可序列化的对象。但是比以前的选项更容易实现

    • 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
    • 这篇关于如何在任何对象上使用ES6哈希映射,而不需要引用(即Java哈希码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆