We have multiple ways to Delete the Object property.
Arrow Function: We can also use the arrow function to remove the property from an object which is a one-liner solution.
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
const fn = (key, { [key]: deletedKey, ...others }) => others;
console.log(fn('first', obj)) // { 'second': 'two', 'third': 'three' }
Reduce Method: We can use the reduce method to delete the specific property from the original object in javascript.
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
const exceptSecond = Object.keys(obj).reduce((acc, key) => {
if (key !== 'second') {
acc[key] = obj[key]
}
return acc
}, {})
console.log(exceptSecond) // { 'first': 'one', 'third': 'three' }
Delete: This is easy simple way to delete.
delete obj.first;
// Or
delete obj['first'];
Using unset, Omit, Pic Method from "loadash" lib:
import { unset } from 'lodash'
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
unset(obj, 'third') // true
console.log(obj) // { 'first': 'one', 'second': 'two' }
// Using omit
import { omit } from 'lodash'
const obj1 = {
'first': 'one',
'second': 'two',
'third': 'three'
}
omit(obj1, [ 'first', 'second' ])
console.log(obj1)
Reflect Delete Property: This is the new built-in Object introduced in ES6. Now it is possible to delete object property by calling the deleted property() function from this Refect Object.
This function is equivalent to what we have discussed with the delete operator in the first method.
const someObject = {
'first': 'one',
'second': 'two',
'third': 'three'
}
Reflect.deleteProperty(someObject, 'second')
console.log(someObject) // { 'first': 'one', 'third': 'three' }