Syntax, Parameter and Return Value
Syntax:
_.keyBy(collection, [iteratee=_.identity])
Parameters:
-
collection (Array|Object): The collection to iterate over.
- [iteratee=_.identity] (Function): The iteratee to determine the key for each element.
Return Value:
(Object) - Returns the composed object.
Examples
Indexing Objects by a Property:
JavaScript
var _ = require('lodash');
var users = [{ 'id': 'abc1', 'name': 'John' },
{ 'id': 'abc2', 'name': 'Jane' }];
var usersById = _.keyBy(users, 'id');
console.log(usersById);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ 'abc1': { 'id': 'abc1', 'name': 'John' }, 'abc2': { 'id': 'abc2', 'name': 'Jane' } }
Demonstrates creating an object with user IDs as keys.
Using a Function to Generate Keys:
JavaScript
var numbers = [6.1, 4.2, 6.3];
var keyedByFloorValue = _.keyBy(numbers, Math.floor);
console.log(keyedByFloorValue);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ '4': 4.2, '6': 6.3 }
Shows keying elements by the integer part of a number.
Grouping Strings by Length:
JavaScript
var strings = ['one', 'two', 'three', 'four'];
var keyedByLength = _.keyBy(strings, 'length');
console.log(keyedByLength);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ '3': 'two', '4': 'four', '5': 'three' }
An example of creating an object with string lengths as keys.
Complex Key Generation:
JavaScript
var items = [{ 'type': 'fruit', 'name': 'apple' },
{ 'type': 'vegetable', 'name': 'carrot' }];
var keyedByTypeAndName = _.keyBy(items, item => `${item.type}-${item.name}`);
console.log(keyedByTypeAndName);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ 'fruit-apple': {...}, 'vegetable-carrot': {...} }
Demonstrates keying objects based on a composite key.
Frequently Asked Questions
What happens if the iteratee produces non-unique keys?
If non-unique keys are produced, each subsequent element with the same key will overwrite the previous one, resulting in only the last element being stored under that key.
Can _.keyBy() be used with nested objects?
Yes, _.keyBy() can be used with nested objects, but the iteratee function needs to be designed to handle the nested structure appropriately.
Is _.keyBy() efficient for large datasets?
_.keyBy() is generally efficient for large datasets, but performance may vary based on the complexity of the iteratee function and the size of the dataset.
Conclusion
Lodash's _.keyBy() method is an efficient and convenient tool for reorganizing collections into objects keyed by specific properties or custom criteria. It greatly simplifies data structuring and enhances the accessibility of elements within collections.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.