Using Lodash's omit() Function
Given an object obj
and an array of strings paths
, Lodash's pick()
function returns a new object
with all the keys in obj
that are not in paths
.
omit()
is the opposite of Lodash's pick()
function.
const obj = {
name: 'Will Riker',
rank: 'Commander',
age: 29
};
const newObj = _.omit(obj, ['rank', 'age']);
newObj === obj; // false
newObj.name; // 'Will Riker'
newObj.rank; // undefined
newObj.age; // undefined
omit()
will not throw any errors if you try to omit paths that don't exist.
const obj = {
name: 'Will Riker',
rank: 'Commander',
age: 29
};
// Works fine even though 'something else' isn't a path in `obj`
const newObj = _.omit(obj, ['rank', 'age', 'something else']);
newObj === obj; // false
newObj.name; // 'Will Riker'
newObj.rank; // undefined
newObj.age; // undefined
Dotted Paths
Like pick()
, omit()
supports dotted paths and other syntaxes that Lodash's get()
function supports.
You can omit properties underneath objects, and even individual array elements.
const obj = {
name: {
first: 'Will',
last: 'Riker'
},
rank: 'Commander',
ships: ['USS Enterprise', 'USS Pegasus'],
age: 29
};
const newObj = _.omit(obj, ['name.first', 'age', 'ships.1']);
newObj === obj; // false
newObj.name.first; // undefined
newObj.name.last; // 'Riker'
newObj.rank; // 'Commander'
newObj.ships; // ['USS Enterprise',] Note that index 1 is an array hole
newObj.age; // undefined
Vanilla JS Alternatives
If all you want to do is omit some top-level keys from an object, you might not need Lodash.
There are several ways to replicate omit()
without Lodash, excluding dotted paths and other advanced functionality.
The most concise way is to use an anonymous arrow function combined with the spread operator as follows.
const obj = {
name: 'Will Riker',
rank: 'Commander',
age: 29
};
// Looks tricky, but the idea is that you're calling an anonymous arrow
// function that uses the spread operator to get all properties _other than_
// `rank` and `age`.
const newObj = (({ rank, age, ...rest }) => rest)(obj);
newObj === obj; // false
newObj.name; // 'Will Riker'
newObj.rank; // undefined
newObj.age; // undefined
The above approach is concise, but hard to read, especially for beginners. You can also implement a short helper function as follows.
function omit(obj, keys) {
const ret = {};
keys = new Set(keys);
const keysToCopy = Object.keys(obj).filter(key => !keys.has(key));
for (const key of keysToCopy) {
ret[key] = obj[key];
}
return ret;
}