Search code examples
javascriptsetidentityecmascript-6ecmascript-harmony

JavaScript sets and value objects


I want to create a set of value objects in JavaScript. The problem is that in JavaScript equality is based on identity. Hence, two different objects with the same value will be treated as unequal:

var objects = new Set;

objects.add({ a: 1 });
objects.add({ a: 1 });

alert(objects.size);   // expected 1, actual 2

How do you work around this problem?


Solution

  • Use JSON.stringify:

    var objects = new Set;
    
    objects.add(JSON.stringify({ a: 1 }));
    objects.add(JSON.stringify({ a: 1 }));
    
    alert(objects.size);