Categories
JavaScript Answers

How to Filter Keys of an Object with Lodash?

Spread the love

Sometimes, we may want to extract some properties from an object and put them into a new object with Lodash.

In this article, we’ll look at how to get an object with only some of the keys from the original object.

Use the pickBy Method

Lodash comes with the pickBy method that takes an object and a callback that lets us return the condition of the keys we want to keep.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.pickBy(thing, (value, key) => {
  return _.startsWith(key, "a");
});
console.log(result)

Then we return an object with the properties from thing that starts with 'a' .

The first argument of pickBy is the object that we want to extract properties from.

The 2nd argument is the callback that returns the condition of the properties of the keys that we want to extract.

Then result is:

{
  "a": 123,
  "abc": 6789
}

Use the omitBy Method

We can also use the Lodash omitBy method to do the same thing.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.omitBy(thing, (value, key) => {
  return !_.startsWith(key, "a");
});
console.log(result)

The arguments are the same as pickBy except that the callback returns the condition for the keys that we don’t want in the returned object.

Therefore, result is the same as before.

Conclusion

We can use the pickBy or omitBy Lodash methods to extract the keys from an object and return an object with the properties we want from the original object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *