0

Here is the result in REPL

>>a1={1:2}
Object {1: 2}
>>a2={1:4}
Object {1: 4}
>>c={}
Object {}
>>c[a1]=2
2
>>c[a2]
2

As can be seen, a1 and a2 are different objects. However, c[a1] and c[a2] will get the same result. Is there a way to use object as the key of a hashmap?

Hanfei Sun
  • 39,245
  • 33
  • 107
  • 208
  • I hope this link can help you http://stackoverflow.com/questions/10892322/javascript-hashtable-use-object-key/10908885#10908885 – bugbuilder Mar 10 '15 at 06:22

2 Answers2

0

Only strings can be used as object keys. You could go the hacky route and use JSON.stringify() to turn the objects into strings, but your best bet is to use an actual hashmap.

You could use a custom implementation of one, or if your target environment supports it, use a WeakMap.

There's also a shim for WeakMap that you can use in environments that don't support it yet:

https://github.com/polymer/WeakMap

JLRishe
  • 90,548
  • 14
  • 117
  • 150
-1

You can convert the object to a string. The type of keys in a javascript object should be a string

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

You can find the same example in the above link.

c[<some_func_to_convert_obj_to_string(a1)>]=2

So If you want to use the object as a key you need to convert the object to a unique string.. and there are many answers here for that Converting object to string . As Steven Wexler pointed out that JSON.stringify is non deterministic it is better not to use it. I am not copying down those functions again because there is a dedicated SO question for that.

Srinath
  • 3,194
  • 2
  • 17
  • 36
  • 1
    Using JSON.stringify to create keys can be dangerous because JSON.stringify is not deterministic. – Steven Wexler Mar 10 '15 at 06:18
  • @StevenWexler Or as the OP wants to use an object to as a key ... it should be converted to a string such that that string maps only to this object... There is a SO qsn for that https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string – Srinath Mar 10 '15 at 06:24
  • 1
    The following statement: `JSON.stringify(myObj) === JSON.stringify(myObj)` is not always true because JSON.stringify is not deterministic. So yes, you can create strings from objects with JSON.stringify. But it's dangerous to use these strings as keys. – Steven Wexler Mar 10 '15 at 06:32
  • @StevenWexler Ohh ohk... I am not telling that he should use JSON.stringify ... As already mentioned there are other ways of converting object to a unique string other than JSON.stringify and there is a SO qsn for that ... – Srinath Mar 10 '15 at 06:42