In the Lodash library, there is a very useful function called _.keyBy that helps convert an array of objects into an object, where each key corresponds to the value of a specific property of the objects in the array, and the corresponding value is the original object itself.
How to Use _.keyBy
_.keyBy function requires two parameters:
- Collection (array)
- Iteratee function or property name (used to specify which property of the objects should be used as the new object's key)
Example
Assume we have the following array containing information about multiple employees, and we want to organize this data by employee ID:
javascriptconst employees = [ { id: 'a1', name: 'Alice', age: 25 }, { id: 'b2', name: 'Bob', age: 30 }, { id: 'c3', name: 'Clara', age: 28 } ];
We use _.keyBy to reorganize this array by the id property of the employees:
javascriptconst _ = require('lodash'); const employeesById = _.keyBy(employees, 'id'); console.log(employeesById);
The output will look like this:
json{ "a1": { "id": "a1", "name": "Alice", "age": 25 }, "b2": { "id": "b2", "name": "Bob", "age": 30 }, "c3": { "id": "c3", "name": "Clara", "age": 28 } }
Application Scenarios
This method is particularly suitable for scenarios where you need to quickly look up objects based on a specific key value, such as id. For example, in web development, it is common to quickly retrieve user information based on user ID, and using _.keyBy can significantly improve lookup efficiency.
Summary
By using Lodash's _.keyBy, you can easily convert an array into a key-value mapped object, which enhances data accessibility and operational efficiency when handling large datasets.