EN
JavaScript - set of objects
1 answers
0 points
I'd like to have a set of objects that contains only unique objects. However, in my case I also need the keys to be objects.
I've read that Javascript casts property names to strings, so I guess I can't use set[object] = true
.
Any ideas?
1 answer
0 points
Since ES6 you can use native Set
object type.
xxxxxxxxxx
1
let mySet = new Set();
2
let a = {};
3
let b = {};
4
5
mySet.add(a);
6
7
console.log(mySet.has(a)); // true
8
console.log(mySet.has(b)); // false
Note that a
and b
may have the same value but they are not the same objects in the operating memory (they have different references):
xxxxxxxxxx
1
let mySet = new Set();
2
let a = { id: 1 };
3
let b = { id: 1 };
4
5
mySet.add(a);
6
mySet.add(b);
7
8
for (const item of mySet) {
9
console.log(JSON.stringify(item));
10
}
See also
References
0 commentsShow commentsAdd comment