I would like to delete a property and return a new object without mutating the original object.
I know we can do this easily with Lodash like this:
const profile = { name: 'Maria', age: 30 }
_.omit(profile, name) // it returns a new object without the property name {age: 30}
However, I would like to know if it's possible to do it with vanilla JavaScript without assigning that value to undefined
or using a filter
?
For a single key you can destructure the object, and use computed property with rest to create an object without the property:
const omitSingle = (key, { [key]: _, ...obj }) => obj
const profile = { name: 'Maria', age: 30 }
const result = omitSingle('name', profile)
console.log(result)
To omit multiple properties, you can convert the object to [key, value] pairs, filter the pairs according to the listed keys array, and then convert back to an object via Object.fromEntries()
:
const omit = (keys, obj) =>
Object.fromEntries(
Object.entries(obj)
.filter(([k]) => !keys.includes(k))
)
const profile = { name: 'Maria', gender: 'Female', age: 30 }
const result = omit(['name', 'gender'], profile)
console.log(result)
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