Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get deep-equality of keys in ES6 Map? Alternative to using complex object as ES6 Map key?

Here is some example Javascript (ES6) code that does not do what one might intuitively imagine.

const exampleMap = new Map([[{a: 1}, 2]]);
console.log(exampleMap.get({a: 1}));

As it turns out, this prints undefined. Why? The reasoning is covered in this StackOverflow answer. Per the MDN entry for Map, Map uses === for key equality. And, per the MDN entry for ===, Objects are compared by reference equality.

That's all fine and good. It does exactly what the docs say it should. Unfortunately, what the above code is trying to do would be quite useful, even if it isn't the actual behavior per the spec.

How can I use Map, or what should I use instead of Map, to get a key-value lookup where the keys are compared by object deep-equality semantics?

like image 477
Ming Avatar asked Dec 19 '25 11:12

Ming


1 Answers

You could create your own function, where you pass through the map (m) you want to get the value of, and a key you want to search in the map. You can then stringify your key, such that you can search the keys in your map and compare them against this stringified key

const exampleMap = new Map([[{a: 1}, 2]]);

const getMapVal = (m, key) => {
  const strKey = JSON.stringify(key);
  return m.get(Array.from(m.keys()).find((k) => JSON.stringify(k) === strKey));
}

console.log(getMapVal(exampleMap, {a: 1})); // 2 (gives undefined if key doesn't exists)
like image 172
Nick Parsons Avatar answered Dec 22 '25 01:12

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!