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

Well, ECMAScript 6

Set lets you add objects to sets.

how

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

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

      

Determining if there is a "scalar" element (like c) is simple:

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

      

How about the same, but for object elements? I would have thought that providing has () with a toString()

value object would return true, but that is not

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

      

If Sets can contain objects, then it has()

must know to determine if a given object is contained. But how?

Refresh . Although the solution to the script above is also straight forward ( s.has(o)

), as far as adding an object on the fly to s, that you don't have a reference? In that case, you can determine if s

this object contains ?

+3


source to share


1 answer


You can use the object directly, without fluff:

s.has(o);

      

This will return true.

This works because s

Set contains a reference to the object o

, so the function has to simply check that the reference of the object passed to 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}));

      

The result is false

that both objects have the same content, but they are all different. If you want to check that the set contains an object with certain content, then for this you need to write your own code. The simplest algorithm:

  • iteration over all elements in the set
    • if the content is the same; return true

  • if we don't come back β†’ return false

+6


source







All Articles