Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?
If you already use lodash, you may also do omit(obj, ["properties", "to", "omit"])
to get a new Object without the properties provided in the array.
Omit and array of keys, using ES7 w/ recursion.
function omit(keys, obj) {
if (!keys.length) return obj
const { [keys.pop()]: omitted, ...rest } = obj;
return omit(keys, rest);
}
This builds on top of @Eddie Cooro answer.
One solution, I'm sure many others exist.
const testObj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3'
};
const removeProps = (...propsToFilter) => obj => {
return Object.keys(obj)
.filter(key => !propsToFilter.includes(key))
.reduce((newObj, key) => {
newObj[key] = obj[key];
return newObj;
}, {});
};
console.log(removeProps('prop3')(testObj));
console.log(removeProps('prop1', 'prop2')(testObj));
Edit: I always forget about delete
...
const testObj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3'
};
const removeProps = (...propsToFilter) => obj => {
const newObj = Object.assign({}, obj);
propsToFilter.forEach(key => delete newObj[key]);
return newObj;
};
console.log(removeProps('prop3')(testObj));
console.log(removeProps('prop1', 'prop2')(testObj));
If you know the list of the properties that you want preserved as well as omitted, the following "whitelisting" approach should work:
const exampleFilter = ({ keepMe, keepMeToo }) => ({ keepMe, keepMeToo })
console.log(
exampleFilter({
keepMe: 'keepMe',
keepMeToo: 'keepMeToo',
omitMe: 'omitMe',
omitMeToo: 'omitMeToo'
})
)
Sure, why not something like:
var original = {
name: 'Rory',
state: 'Bored',
age: '27'
};
var copied = Object.assign({}, original);
delete copied.age;
console.log(copied);
https://jsfiddle.net/4nL08zk4/
There's the blacklist
package on npm which has a very flexible api.
Also a situational trick using the object rest-spread proposal (stage-3).
const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
a // 1
b // 2
rest // {c: 3, d: 4}
This is often used in react components where you want to use a few properties and pass the rest as props to a <div {...props} />
or similar.