How to use keyBy() function In Lodash

In this approach, we are using Lodash’s keyBy() function with the ‘id’ property as the key identifier to create a hash map where each object’s ‘id‘ is the key, allowing for retrieval of objects by their IDs and simplifying data access and manipulation.

Syntax:

_.keyBy(collection, [iteratee=_.identity])

Example: The below example uses the keyBy function to Convert an object array to a hash map using lodash

JavaScript
const _ = require('lodash');
let courses = [{
        id: 101,
        name: 'Programming with Python'
    },
    {
        id: 102,
        name: 'Data Structures and Algorithms'
    },
    {
        id: 103,
        name: 'Web Development with JavaScript'
    }
];
let res = _.keyBy(courses, 'id');
console.log(res);

Output:

{
'101': { id: 101, name: 'Programming with Python' },
'102': { id: 102, name: 'Data Structures and Algorithms' },
'103': { id: 103, name: 'Web Development with JavaScript' }
}

How to Convert Object Array to Hash Map using Lodash ?

Converting an Object Array to a Hash Map consists of manipulating the array elements to create a key-value mapping.

Below are the different approaches to Converting an object array to a hash map using Lodash:

Table of Content

  • Using keyBy() function
  • Using reduce function

Run the below command before running the below code on your system:

npm i lodash

Similar Reads

Using keyBy() function

In this approach, we are using Lodash’s keyBy() function with the ‘id’ property as the key identifier to create a hash map where each object’s ‘id‘ is the key, allowing for retrieval of objects by their IDs and simplifying data access and manipulation....

Using reduce function

In this approach, we are using Lodash’s reduce function to iterate over the courses array and build a hash map where each object’s ‘id‘ serves as the key, resulting in a convenient key-value mapping for object retrieval and data organization....