Set
objects are collection of values.
// Create a Set const someSet = new Set(["a","b"]); // adding element someSet.add("c"); console.log(someSet); // ["a","b","c"] // adding existing element, rejected someSet.add("c"); console.log(someSet); // ["a","b","c"] // checking item existence someSet.has("a"); // true someSet.has("d"); // false
Objects added to Set
are not unique by value.
const nSet = new Set(); nSet.add({name:'a', value: 'b'}); nSet.add({name:'a', value: 'b'}); console.log(nSet); // {Object {name: "a", value: "b"}, Object {name: "a", value: "b"}}
You need to stringify them to keep uniqueness.
nSet.add(JSON.stringify({name:'a', value: 'b'})) nSet.add(JSON.stringify({name:'a', value: 'b'})) const formattedSet = [...nSet].map(item) => { if (typeof item === 'string') return JSON.parse(item); else if (typeof item === 'object') return item; });