Canet Robern
Canet Robern

Reputation: 1069

Javascript - Removing object key not using delete

This might be duplicated question, but I could not find any.

I wanna remove a key of an object.

Please check my fiddle first.

Remove a key of an object

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

Answers (2)

Prasanna
Prasanna

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

James Courson
James Courson

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

Related Questions