Veverke
Veverke

Reputation: 11378

How to determine if a Set contains an object without reference (added on the fly to the set) in Javascript (ECMAScript 6)

Well, ECMAScript 6 Set allows adding objects into sets.

Like

var s = new Set();
var o = {a: 1, b: 2};

s.add(o);
s.add("c");

Determining if a "scalar" element (like c) is present is straightforward:

s.has("c"); // true

What about the same but for object elements ? I would think providing has() with the object's toString() value would return true, but it does not

o.toString() // -> "[object Object]"
s.has("[object Object]") // -> false

If Sets can contain objects, then its has() must know to determine whether a given object is contained. But how ?

Update: Although the solution to the scenario depicted above is just as well straightfoward (s.has(o)), what about adding an object on the fly to s, to which you do not have a reference ? In such a case, can you still determine if s contains that object ?

Upvotes: 3

Views: 76

Answers (1)

meskobalazs
meskobalazs

Reputation: 16041

You can use the object directly, no fluff:

s.has(o);

This will return true.

This works, because the s Set holds a reference to the o object, so it the has function simply has to check that the reference of the object passed in, is held by the set.

Object without "lost" reference

If you add an object literal like

var s = new Set();
s.add({a: 1, b: 2});
console.log(s.has({a: 1, b: 2}));

This results in false, as the two objects have the same content, but they are different objects altogether. If you would like to test, that the set contains an object, with specific content, then you have to write your own code for that. The simplest algorithm would be:

  • iterate through all elements in the set
    • if the contents are the same → return true
  • if we did not return → return false

Upvotes: 6

Related Questions