Build lodash.omit from Scratch with forEach and for...in

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

_.omit and its sibling _.pick are popular utilities which apply filter-like functionality to objects. This lesson will demonstrate two techniques for building the functionality found in _.omit.

  • Cloning the object with Object.assign and removing unwanted keys with delete
  • Using for...in and .includes to manually copy keys into a result object

Notes:

In modern JavaScript environments instead of Object.assign({}, obj) you can also use { ...obj } which will have the same effect of a shallow copy.

This lesson will not cover how to emulate _.omit's support for taking either an array or multiple arguments for its keys, but our video on building _.pick from scratch covers one approach.


Instructor: [0:00] In a file called omit.js, type function omit and pass in two arguments, obj and keys. The first thing that we're going to do inside this function is create a shallow copy of our object by typing const result = object.assign(emptyObject, obj). We'll return that result.

[0:23] Just before our return, let's loop through our keys by typing keys.forEach(key). For each one of those keys, delete result key. We start by copying the object, then we go through each of the keys we don't want to in our object and delete them from the result. Pretty straightforward.

[0:43] Let's create a second event function, this time called omit to. We'll take the same arguments, obj and keys. Inside of that, we'll create an empty object for result and return the result. Right before our return statement, type for (let key in obj). Then, if not keys.includes(key) results(key) = (obj, key).

[1:08] For each of the keys in our object, we're going to loop through those. If the key that we're currently looping through is not included in the list of keys, then we'll go ahead and copy that over into our result object.

[1:22] To prove that this works, I've got an object here with a few letters from the alphabet. We'll test against that by typing console.log(omit(obj)) and we'll pass in the array B, C, D. We will do the same thing down here for omit to. Let's run that, node./omit.js and we're seeing exactly right. Only the A and E keys remain.