Open In App

How to Convert Object Array to Hash Map using Lodash ?

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

npm i lodash

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.

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' }
}

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.

Syntax:

_.reduce(collection, iteratee, accumulator)

Example: The below example uses the reduce 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 = _.reduce(courses, (result, course) => {
    result[course.id] = course;
    return result;
}, {});
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' }
}

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads