Alternative to lodash omit
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 don't have a nested object, try to clone as follows:
const profile = { name: 'Maria', age: 30 }
function deleteProperty(object, property){
var clonedObject = JSON.parse(JSON.stringify(object));
delete clonedObject[property];
return clonedObject;
}
var newProfile = deleteProperty(profile, "name");
console.log(profile);
console.log(newProfile);
const obj = {
prop0: 0,
prop1: 1,
prop2: 2,
prop3: 3,
};
const prunedObj = (({ prop1, prop2, ...rest }) => rest)(obj);
// prunedObj => { prop0: 0, prop3: 3}