How can I remove a key from an Object, Immutably, except key name is not known until you perform the removal?

Viewed 55

I know I can use the rest operator to remove a key from an Object, such as

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

But what if the key name is not known until run time (For example a randomly generated ID)

const myobject = {
  cke503: { Fake: '1' },
  cke502: { Fake: '2' },
  cke501: { Fake: '3' },
};

I dont know the ID's until runtime, so I use const id = Object.Keys(myobject)[2] to get 'cke501'

    const id = Object.Keys(myobject)[2] // -> 'cke501'
    const { [id], ...rest } = myobject; // -> This doesn't work

2 Answers

You'll need to specify a variable name to put the value into, but variable names can't be dynamic, so you'll have to use syntax very similar to computed properties, const { [prop]: propVal, ...noA } = myObject;:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const prop = 'a'; // Substitute this with the runtime property calculation
const { [prop]: propVal, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }
console.log(propVal);

Does this work for you?

const myobject = {
    cke503: { Fake: '1' },
    cke502: { Fake: '2' },
    cke501: { Fake: '3' },
};
const id = Object.keys(myobject)[2] // -> 'cke501'
const { ...rest } = myobject;
delete rest[id];
Related