Home > Software engineering >  JavaScript Map with objects for keys: duplicate entries
JavaScript Map with objects for keys: duplicate entries

Time:01-15

According to the mdn webdocs on JavaScript's Map:

A Map's keys can be any value (including functions, objects, or any primitive).

However:

const map = new Map();
console.log(map.size); // 0

map.set({someProperty: 0}, 0);
console.log(map.size); // 1

map.set({someProperty: 0}, 0);
console.log(map.size); // 2 <-- what? shouldn't this be 1 still?

The documentation indicates that it's fine to use an object as a key. So how can I insert an object with the same key into the Map?

CodePudding user response:

The two objects have different references.

If you use the same object both times, you only have one entry:

const map = new Map();
const key = { someProperty: 0 };
map.set(key, 0);
map.set(key, 0);
console.log(map.size);

CodePudding user response:

Every object is unique (even if its keys and values are identical to those of another one), so when you use different objects as keys, each will occupy a different entry in the Map.

See more at Equality comparisons and sameness on MDN.

const map = new Map();
console.log(map.size); // 0

const a = {someProperty: 0};
const b = {someProperty: 0};

console.log(a === b); // false

map.set(a, 0);
console.log(map.size); // 1

map.set(b, 0);
console.log(map.size); // 2

const c = a;

console.log(a === c); // true

map.set(c, 1);
console.log(map.size); // 2

console.log(map.get(a)); // 1 (not 0)

  • Related