1

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?

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • 3
    See http://stackoverflow.com/questions/27094680/user-defined-object-equality-for-a-set-in-harmony-es6 – elclanrs Mar 26 '15 at 06:24
  • @elclanrs The only problem with that is the overhead associated with stringifying and parsing data. – Aadit M Shah Mar 26 '15 at 06:28
  • In one of my libraries, I have my own Map implementation, which is at least API compatible. I simply use the `toString` method as has function, which allows me to treat arrays (of primitives) like tuples. That doesn't work out of the box for objects of course. – Felix Kling Mar 26 '15 at 06:34
  • Why use sets when MDN says specifically that `The Set object lets you store unique values of any type, whether primitive values or object references.` (note `unique`). Either have something different about the objects or don't use sets. – Bardi Harborow Mar 26 '15 at 08:06
  • @BardiHarborow Why use sets? I want a set of value objects, that's why. I know what the specification says, thank you very much. Uniqueness is guaranteed by the `Set` data type itself and not what you add to it. For example, `var i = 0; while (i < 10) objects.add(1);` will only add `1` to the set `objects` once. What do you mean by "have something different about the objects"? I don't want to have anything different about the objects. I want them to be the same object without having to worry about them having the same identity. Don't use sets? Well, thank you very much. That solves my problem. – Aadit M Shah Mar 26 '15 at 09:03
  • @BardiHarborow In what world would any sane person want two same valued objects to be repeated in a set? – Aadit M Shah Mar 26 '15 at 11:41
  • Yeah, well, that's exactly why my response was so sharp. Sorry about that. – Bardi Harborow Mar 28 '15 at 01:03
  • @BardiHarborow Then why are you arguing? You make absolutely no sense whatsoever. – Aadit M Shah Mar 28 '15 at 01:52

1 Answers1

3

Use JSON.stringify:

var objects = new Set;

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

alert(objects.size);
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
Vivek Gupta
  • 955
  • 4
  • 7