3 ms·
JS does indeed allow mapping arbitrary objects to keys. However, it is the memory address of the object that is hashed, not the semantic value. So, for example,
by tibbar 3y ago
JS does indeed allow mapping arbitrary objects to keys. However, it is the memory address of the object that is hashed, not the semantic value. So, for example, if you do:
objects = {}
items1 = ["a", "b"]
items2 = ["a", "b"]
objects[items1] = 1
objects[items2] = 2
then objects[items1] will return 1, and objects[items2] will return 2, but objects[items1] !== objects[items2].
EDIT: Sorry, this only works for dictionaries that are Maps, not Objects! See the responses. My fuzzing about in the console led me astray; you should start with `objects = new Map()` instead of `objects = {}`.
- thegeomaster 3y agoThis is not true. I think you're confusing JS objects with Maps. This will just coalesce the key to string and overwrite one element of the object with the other. With a map it works like you described: objects = new Map() items1 = ["a", "b"] items2 = ["a", "b"] objects.set(items1, 1) objects.set(items2, 2)
- mediumdeviation 3y agoActually that only works with Map. For plain objects the key is always the stringified cast of the key. > o = { [{}]: 1 } { '[object Object]': 1 } > k = { toString() { return 'a' } } { toString: [Function: toString] } > o = { [k]: 1 } { a: 1 }
- aragonite 3y agoRight ... and it seems it's not even possible to simulate object keys using Proxy traps: new Proxy( {}, { get(target, property) { return typeof property }, }, )[{}] === 'string'
- koito17 3y agoAh, I didn't know Map in JavaScript allowed arbitrary keys whereas Object always serializes to strings. I guess that is the reason for having a Map.groupBy in the proposal. Thanks for taking the time to explain, everybody