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
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 .
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.
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.
A better way to delete a property without mutating is by using spread operator. const {worth, … newPerson} = person; console.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With