Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.pick() Object Method

Posted in lodash Tutorial
Updated on Oct 30, 2024
By Mari Selvan
👁️ 97 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.pick() Object Method

Photo Credit to CodeToFun

🙋 Introduction

In the realm of JavaScript programming, working with objects is a common task. However, dealing with large or complex objects often requires extracting specific properties of interest. This is where the _.pick() method from the Lodash library comes into play.

_.pick() enables developers to select and extract only the desired properties from an object, streamlining data manipulation and enhancing code clarity.

🧠 Understanding _.pick() Method

The _.pick() method in Lodash allows you to extract specified properties from an object, creating a new object with only those properties included. This selective extraction simplifies data handling, reducing complexity and improving readability in your code.

💡 Syntax

The syntax for the _.pick() method is straightforward:

syntax.js
Copied
Copy To Clipboard
_.pick(object, [props])
  • object: The source object from which properties are to be picked.
  • props: The property names to pick.

📝 Example

Let's dive into a simple example to illustrate the usage of the _.pick() method:

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

const sourceObject = {
  name: 'John Doe',
  age: 30,
  email: 'john@example.com',
  isAdmin: true,
};

const pickedProperties = _.pick(sourceObject, ['name', 'email']);

console.log(pickedProperties);
// Output: { name: 'John Doe', email: 'john@example.com' }

In this example, the sourceObject is filtered using _.pick() to create a new object containing only the specified properties.

🏆 Best Practices

When working with the _.pick() method, consider the following best practices:

  1. Specify Target Properties:

    Be explicit about which properties you want to extract using _.pick(). This ensures clarity in your code and prevents unintended inclusion or exclusion of properties.

    example.js
    Copied
    Copy To Clipboard
    const user = {
      name: 'Alice',
      age: 25,
      email: 'alice@example.com',
      isAdmin: false,
    };
    const filteredUser = _.pick(user, ['name', 'email']);
    console.log(filteredUser);
    // Output: { name: 'Alice', email: 'alice@example.com' }
  2. Handle Non-existent Properties:

    Ensure that the properties you intend to pick exist in the source object. Handling non-existent properties gracefully prevents errors and maintains code robustness.

    example.js
    Copied
    Copy To Clipboard
    const user = {
      name: 'Bob',
      age: 30,
    };
    
    const pickedUser = _.pick(user, ['name', 'email']); // 'email' property does not exist
    
    console.log(pickedUser);
    // Output: { name: 'Bob' }
  3. Avoid Mutating Source Object:

    Remember that _.pick() does not modify the source object; it creates a new object with the selected properties. Avoid relying on side effects and ensure that your source object remains unchanged.

    example.js
    Copied
    Copy To Clipboard
    const originalObject = {
      prop1: 'value1',
      prop2: 'value2',
    };
    
    const pickedObject = _.pick(originalObject, ['prop1']);
    
    console.log(originalObject);
    // Output: { prop1: 'value1', prop2: 'value2' }

📚 Use Cases

  1. Data Filtering:

    _.pick() is invaluable for filtering out unnecessary data properties, especially when dealing with large or nested objects. This streamlines data processing and optimizes memory usage.

    example.js
    Copied
    Copy To Clipboard
    const userData = {
      id: '123',
      name: 'John Doe',
      email: 'john@example.com',
      password: 'hashedpassword',
      isAdmin: true,
      // Other properties...
    };
    
    const filteredUserData = _.pick(userData, ['id', 'name', 'email']);
    
    console.log(filteredUserData);
  2. Object Transformation:

    When transforming objects for specific purposes, _.pick() allows you to select only the relevant properties, simplifying the transformation process and improving code maintainability.

    example.js
    Copied
    Copy To Clipboard
    const rawApiResponse = {
      status: 'success',
      data: {
        id: '456',
        name: 'Jane Doe',
        email: 'jane@example.com',
        // Other properties...
      },
    };
    
    const transformedResponse = {
      status: rawApiResponse.status,
      userData: _.pick(rawApiResponse.data, ['id', 'name', 'email']),
    };
    
    console.log(transformedResponse);
  3. API Responses:

    In API development, _.pick() can be used to tailor response objects, sending only the necessary data to clients. This reduces bandwidth usage and enhances API performance.

    example.js
    Copied
    Copy To Clipboard
    app.get('/user/:id', (req, res) => {
      const userId = req.params.id;
      const user = /* ...fetch user data from database or elsewhere... */;
    
      const responseData = _.pick(user, ['id', 'name', 'email']);
      res.json(responseData);
    });

🎉 Conclusion

The _.pick() method in Lodash provides a convenient solution for extracting specific properties from objects in JavaScript. Whether you're filtering data, transforming objects, or customizing API responses, _.pick() empowers you to efficiently manipulate object data with precision and clarity.

By adhering to best practices and exploring diverse use cases, you can harness the full potential of the _.pick() method in your Lodash projects.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy