0

My goal is to use JavaScript Set to store objects of the same type.

However, I run in to problems with using Object within Set.

For the following code:

const mySet1 = new Set();

mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add("some text"); // Set(3) { 1, 5, 'some text' }
const o = { a: 1, b: 2 };
mySet1.add(o);
mySet1.add({ a: 'b' })

I am able to verify values with has for string values or object references, such as

mySet1.has(5)  // true
mySet1.has(o)  // true

However, I am unable to verify values with has for indirect references to object values, such as:

mySet1.has({ a: 'b' }) // false

How can I otherwise verify that { a: 'b' } exists on mySet1?

Elise Chant
  • 5,048
  • 3
  • 29
  • 36

1 Answers1

0

That's because the has compares all entries in the set using a equality check.

But in JavaScript, quen using a equality ooerator with two different objects with same content, it will return false.

Why? Because JavaScript won't do a deep comparison on object, instead it will check if the operands points to same object.

For example:

const a = {foo: 1}
const b = {foo: 1}

// Internally has do this:
a === b // false

// But on your working like `.has(o)`
// You are comparing the object with itself:

o === o // true
Elias Soares
  • 9,884
  • 4
  • 29
  • 59