Reputation: 69
I would appreciate assistance regarding how to remove/delete a specific object from a Set in JavaScript. I have not been able to find the answer to this seemingly simple question online. Please see the following simple example Set:
let mySet = new Set([1, 2, {Name: "Ann"}]);
Set(3) {1, 2, {…}}
mySet.delete(1);
console.log(mySet);
Set(2) {2, {…}}
// The basic syntax above doesn't seem to delete an object within a Set. I have tried the following, none of which removed the object:
mySet.delete({"Name": "Ann"});
false
mySet.delete("Name");
false
mySet.delete("Ann");
false
Is there a different approach that will remove a specific object from a Set in JavaScript? Perhaps a for...of loop, but then how to specify the specific object for removal? Any help would be greatly appreciated. :)
Upvotes: 6
Views: 10196
Reputation: 579
If you're able to initialise the object before passing it to Set
. And retain reference to is (i.e. scope);
const person = { name: "Ann" };
const my_set = new Set([1, 2, person]);
my_set.has(person); //true
my_set.delete(person);
my_set.has(person); // false
Otherwise;
const my_set = new Set([1, 2, { name: "Ann" }]);
my_set.forEach(item => { if (item.name === "Ann") my_set.delete(item); });
Upvotes: 5
Reputation: 85
What I usually do is,
* Careful since this considers order of keys.
You can use this function:
function removeObjectFromSet (set, obj) {
return new Set([...set].filter((el) => JSON.stringify(el) != JSON.stringify(obj)))
}
For example, like this:
let mySet = new Set([1, 2, { Name: "Ann" }])
mySet = removeObjectFromSet(mySet, { Name: "Ann" })
console.log(mySet)
Upvotes: 1
Reputation: 18525
The Set object lets you store unique values of any type, whether primitive values or object references.
So this will simply add 2 objects to Set
since they do not have the same object references.
var mySet = new Set([{Name: "Ann"}, {Name: "Ann"}]);
console.log(mySet.size) // 2
You might as well use an array in this case.
So in this scenario to remove Ann
(since we do not have an object reference) we would have to:
var mySet = new Set([1, 2, "abc", {Name: "Ann"}]);
console.log('With Ann size:', mySet.size)
mySet.forEach(x => x.Name === 'Ann' ? mySet.delete(x) : x)
console.log('Bye Ann size:', mySet.size)
Now consider this:
var ann = {Name: 'Ann'}
var mySet = new Set([ann, ann])
console.log('With Ann size:', mySet.size)
mySet.delete(ann)
console.log('Bye Ann size:', mySet.size)
So as you can see we are now dealing with object references and firstly the size is only 1 and the Set
can now find ann
reference and remove it with no issues.
Upvotes: 9