Search code examples
javascripttypescriptecmascript-6ecmascript-5ecma

Delete a dynamic key from a TypeScript object


In TypeScript it is quite simple to clone an object:

const a = {...b}

or clone and update

const a = {...b, c: 'd'}

So for example, I have this code:

const a = {
    'something': 1,
    'e': 2,
};
const c = 'something';
delete a[c];

Is there a nice way to delete a property of that object, instead of using the traditional delete a[c] way? (of course also not a[c] = undefined)


Solution

  • You're looking for combination of computed property names and destructuring. More info here

    const a = {
        'something': 1,
        'e': 2,
    };
    
    const c = 'something';
    
    const { [c]: _, ...withoutC } = a;
    

    Here we're putting value of property something (taken from c variable) into _ variable and all the other props go to withoutC variable. The fact that c defined as const allows typescript to infer the type of withoutC properly.