Prasanna
Prasanna

Reputation: 4636

Using reserved keywords as object key with spread operators

Say I have an object that looks like this

const props = {
    delete: function() {
        // stuffs
    },
    hello: 'hello',
    other: 'other', 
}

Now say I use spread operators and do something like this

const {hello, ...otherStuffs} = props;

Then for otherStuffs, I still get an object that is a copy of props but except for the hello key.

But what if I do not want the delete key of the object ? I can not do the same as done above because apparently delete is a reserved keyword.

const {delete, ...otherStuffs} = props; // error here

I can however still filter the keys from the object that are not equal to 'delete' and get my object but is there a way to do this using spread operators ?

Upvotes: 0

Views: 898

Answers (1)

maazadeeb
maazadeeb

Reputation: 6112

You can do it by aliasing the delete property of props. You can try this

const props = {
    delete: function() {
        console.log("delete");
    },
    hello: 'hello',
    other: 'other', 
}

const {"delete": del, ...otherStuffs} = props;
del();

Reference: Invalid JavaScript identifier as a property name

Upvotes: 3

Related Questions