Reputation: 1069
This might be duplicated question, but I could not find any.
I wanna remove a key of an object.
Please check my fiddle first.
delete obj.something;
When you check console, you'll be able to see the same object is printed in console in spite of using delete after first console.log
.
Why this happening?
And what is the best idea of remove a key of an object?
Thanks in advance.
Upvotes: 2
Views: 1729
Reputation: 4636
you can use spread operators to remove keys.
let obj = {a:1, b:2, c:3}
const {a, ...restObj} = obj; // this will make restObj with deleted a key.
This method is especially useful when dealing with immutable types. This way you would not mutate the original object and still get an object with deleted key
Upvotes: 1
Reputation: 66
You can try obj[key] = undefined;
. It's roughly 100 times faster, according to:
How do I remove a property from a JavaScript object?
Upvotes: 1