
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Object by Keys in Lodash
Sometimes while working with objects in JavaScript we want to filter objects based on keys. We can easily do this by using Lodash, a popular JavaScript library that provides several inbuilt functions to achieve this easily. In this article, we are going to discuss how we can Filter Objects by Keys using Lodash.
Prerequisite
- Lodash: Lodash is a popular JavaScript library used to deal with a variety of functions such as arrays, objects, strings, and more.
Install Lodash
We can install the Lodash library in the project by adding it via CDN or npm using the following command:
npm install lodash
Approaches to filter object by keys in Lodash
Using Lodash's pick() Method
The pick() method in Lodash allows us to select specific keys from an object. It creates a new object containing only the specified keys. This method allows us to extract specific key-value pairs by directly specifying the keys we want to keep.
Example
const _ = require("lodash"); // Original object const obj = { name: "Ayush", age: 21, city: "Kanpur", profession: "Tech Writer" }; // Filter object by keys const filteredObj = _.pick(obj, ["name", "profession"]); console.log(filteredObj);
Output
{ name: 'Ayush', profession: 'Tech Writer' }
Using Lodash's omit() Method
The omit() method is just the reverse of the _.pick() method. In this method instead of selecting specific keys, it excludes the specified keys and keeps the rest. This method loops through the object's keys and checks whether each key is in the exclusion list. If a key is not in the exclusion list, it is added to the result object.
Example
const _ = require("lodash"); // Original object const obj = { name: "Ayush", age: 21, city: "Kanpur", profession: "Tech Writer" }; // Remove keys const filteredObj = _.omit(obj, ["age", "city"]); console.log(filteredObj);
Output
{ name: 'Ayush', profession: 'Tech Writer' }