Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 361
Terry Avatar asked Aug 22 '20 02:08

Terry


People also ask

How do I remove an objects key from an object?

Use delete to Remove Object Keys entries() to access the object keys and values after deleting key and setting key2 to undefined . We can see that because I did not use the delete keyword, key2 still exists on the JavaScript object. The code example also shows the return values from delete .

How do I remove a key from object Lodash?

unset() Method. The Lodash _. unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.

How do you remove undefined keys from an object?

To remove all undefined values from an object:Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete all undefined values using the delete operator.

How do I remove a property from an object without mutating?

A better way to delete a property without mutating is by using spread operator. const {worth, … newPerson} = person; console.

How do I remove a property from an object?

Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.


1 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);
like image 83
CertainPerformance Avatar answered Oct 12 '22 21:10

CertainPerformance