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