I’d like to have a set of objects in Javascript. That is, a data structure that contains only unique objects.
Normally using properties is recommended, e.g. myset["key"] = true
. However, I need the keys to be objects. I’ve read that Javascript casts property names to strings, so I guess I can’t use myset[myobject] = true
.
I could use an array, but I need something better than O(n) performance for adding, finding and removing items.
It needs to be able to tell objects apart by reference only, so given:
var a = {}; var b = {};
then both a
and b
should be able to be added, because they’re separate objects.
Basically, I’m after something like C++’s std::set
, that can store Javascript objects. Any ideas?
Advertisement
Answer
ES6 provides a native Set
:
let s = new Set(); let a = {}; let b = {}; s.add(a); console.log(s.has(a)); // true console.log(s.has(b)); // false