Chu*_*mon 13 javascript object lodash
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}
Run Code Online (Sandbox Code Playgroud)
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?
Ori*_*ori 19
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)Run Code Online (Sandbox Code Playgroud)
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)Run Code Online (Sandbox Code Playgroud)
小智 6
const obj = {
prop0: 0,
prop1: 1,
prop2: 2,
prop3: 3,
};
const prunedObj = (({ prop1, prop2, ...rest }) => rest)(obj);
// prunedObj => { prop0: 0, prop3: 3}
Run Code Online (Sandbox Code Playgroud)