How to Use Lodash keyBy to Create an Object Dictionary
This article explains how the _.keyBy function in the
Lodash JavaScript library transforms an array of items into an object
dictionary. You will learn the underlying mechanics of the method, how
to define lookup keys using property names or custom functions, how the
function handles duplicate keys, and why this pattern is preferred for
optimizing data lookups in JavaScript applications.
What is _.keyBy?
The _.keyBy function is a utility in Lodash that
constructs an object composed of keys generated from the results of
running each element of an input collection through an
iteratee. The corresponding value of each key is the
original item from the array.
The signature is:
_.keyBy(collection, [iteratee=_.identity])collection: The array or collection to iterate over.iteratee: The criterion used to produce the keys. This can be a string property name or a custom callback function.
How _.keyBy Works
Step-by-Step
When you pass an array to _.keyBy, Lodash executes the
following process:
- Initializes an empty object: Lodash creates a new,
empty dictionary object (
{}) to store the results. - Iterates over the collection: It traverses each element in the array from left to right.
- Executes the iteratee: For every element, it
resolves the key:
- If the iteratee is a string, it extracts the
property corresponding to that string name (e.g.,
'id'). - If the iteratee is a function, it passes the current element to the function and uses the returned value as the key.
- If the iteratee is a string, it extracts the
property corresponding to that string name (e.g.,
- Assigns the key-value pair: It sets
accumulator[generatedKey] = currentElement. - Returns the dictionary: Once the iteration is complete, it returns the populated object.
Example 1: Grouping by a Property Name
The most common use case is transforming a list of objects with unique identifiers into a lookup dictionary using a property string:
const users = [
{ id: 'u101', name: 'Alice', role: 'Admin' },
{ id: 'u102', name: 'Bob', role: 'Developer' },
{ id: 'u103', name: 'Charlie', role: 'Designer' }
];
const usersById = _.keyBy(users, 'id');Output:
{
'u101': { id: 'u101', name: 'Alice', role: 'Admin' },
'u102': { id: 'u102', name: 'Bob', role: 'Developer' },
'u103': { id: 'u103', name: 'Charlie', role: 'Designer' }
}Now, instead of using
users.find(u => u.id === 'u102') (an \(O(n)\) search), you can access the user
instantly using usersById['u102'] (an \(O(1)\) lookup).
Example 2: Using a Function Iteratee
If the desired key requires transformation or computation across multiple properties, you can supply a function:
const products = [
{ code: 'app', version: 1, name: 'Alpha' },
{ code: 'app', version: 2, name: 'Beta' }
];
const productsByCompositeKey = _.keyBy(products, item => `${item.code}_v${item.version}`);Output:
{
'app_v1': { code: 'app', version: 1, name: 'Alpha' },
'app_v2': { code: 'app', version: 2, name: 'Beta' }
}Handling Duplicate Keys
Because object keys must be unique, if multiple elements generate the
same key, _.keyBy adopts a last-write-wins
strategy. The element appearing later in the array will overwrite any
earlier elements that share the same key:
const records = [
{ category: 'news', title: 'Post 1' },
{ category: 'news', title: 'Post 2' }
];
const result = _.keyBy(records, 'category');
// Result: { news: { category: 'news', title: 'Post 2' } }If your objective is to preserve all items with matching keys, use
_.groupBy instead, which groups duplicate matches into an
array under each key.