Open In App

How to Filter Keys of an Object with Lodash ?

Filtering Keys of an Object is used for selectively including or excluding keys based on criteria, facilitating data manipulation and customization.

Below are the approaches to filter keys of an object with Lodash:

Installing the Lodash library using the below command:

npm i lodash

Using pick function

In this approach, we are using the pick function from Lodash with an object and an array of keys to include, creating a new object res that contains only the specified keys 'a' and 'c' from the original object obj.

Syntax:

_.pick(object, [props])

Example: The below example uses the pick function to filter the keys of an object with lodash.

const _ = require('lodash');
let obj = { a: 1, b: 2, c: 3 };
let res = _.pick(obj, ['a', 'c']);
console.log(res); 

Output:

{ a: 1, c: 3 }

Using omit function

In this approach, we are using the omit function from Lodash with an object and an array of keys to exclude, creating a new object res that contains all keys except 'b' from the original object obj.

Syntax:

_.omit(object, [props])

Example: The below example uses an omit function to filter the keys of an object with lodash.

const _ = require('lodash');
let obj = { a: 1, b: 2, c: 3 };
let res = _.omit(obj, ['b']);
console.log(res);

Output:

{ a: 1, c: 3 }

Using pickBy function

In this approach, we are using the pickBy function from Lodash with an object and a predicate function, creating a new object res that includes keys based on the condition specified in the predicate, which excludes the key 'b' from the original object obj.

Syntax:

_.pickBy(object, [predicate=_.identity])

Example: The below example uses the pickBy function to filter the keys of an object with lodash.

const _ = require('lodash');
let obj = { a: 1, b: 2, c: 3 };
let res = _.pickBy(obj, (value, key)
  => key !== 'b');
console.log(res); 

Output:

{ a: 1, c: 3 }
Article Tags :