Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Indexing Objects by a Property:
4.2.
JavaScript
4.3.
Using a Function to Generate Keys:
4.4.
JavaScript
4.5.
Grouping Strings by Length:
4.6.
JavaScript
4.7.
Complex Key Generation:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
What happens if the iteratee produces non-unique keys?
5.2.
Can _.keyBy() be used with nested objects?
5.3.
Is _.keyBy() efficient for large datasets?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.keyBy() Method

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Organizing data efficiently is a cornerstone of effective JavaScript programming. Lodash enhances this capability with the _.keyBy() method, which creates an object composed of keys generated from the results of running each element of a collection through a given iteratee. 

Lodash _.keyBy() Method

This article will cover the _.keyBy() method, exploring its syntax, applications, and benefits, all supported by practical examples and FAQs.

Why This Function is Used

The _.keyBy() function is used to transform a collection into an object, with keys based on a specified property or value derived from each element. This method is particularly useful in scenarios where quick lookup of elements based on a unique identifier is required, such as indexing items by IDs, categorizing data for easier access, or converting lists to more searchable formats. It simplifies the process of reorganizing data for optimized retrieval and manipulation.

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

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

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

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

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 DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass