Search code examples
javascriptnode.jsecmascript-6destructuringspread-syntax

removing an arbitarry property from an object, when said property is abstracted as a string


Let's say I have an object myObject with properties a,b,c.

If I want to get rid of property a, I can normally use:

{a, ...rest} = myObject;

And then work with rest, so I can avoid object mutation.

However, I'm dealing with a situation where the name of the property I want to get rid of is abstracted as a string parameter. I can still access said object's property using the brackets syntax, so if:

const stringWithThePropertyName = 'whatever';

then the property would be :

myObject[stringWithThePropertyName]

and that would be equivalent to myObject.whatever . But what if I want to remove said property from the array?

That is to say, given an object, removing an arbitrary property whose name I take as a string parameter, preferably in an immutable way as I would with the usual spread + destructuring sintax.


Solution

  • You can use bracket syntax while destructuring if you define a variable name to put the found value into:

    const myObject = {
      foo: 'foo',
      bar: 'bar',
      baz: 'baz'
    };
    
    const stringWithThePropertyName = 'foo';
    const { [stringWithThePropertyName]:_ , ...rest } = myObject;
    console.log(rest);

    (the _ variable will contain the value at foo, so if you just want the object without foo, just don't use the _ variable)

    Note that this doesn't actually remove the property from the object - it only creates a new object without that property (which is perfectly fine - avoiding unnecessary mutation is often a good idea). If you actually want to remove the property from the original object, use delete:

    delete myObject[stringWithThePropertyName];