Lodash _.keyBy() method

Beginner
⏱️ 6 min read
📚 Updated: May 2026
🎯 3 Code examples
🚀 3 Try-it labs
Lodash

What you’ll learn

  • How _.keyBy(collection, iteratee) builds lookup maps from rows.
  • Why collisions overwrite—and how that differs from groupBy arrays.
  • Using shorthand property iteratees versus custom functions.
  • Try each example in the editor (?tryit=1, 2, 3) with Lodash from a CDN.

Prerequisites

Review _.groupBy() if buckets usually hold multiple rows—switch here only when uniqueness is guaranteed or last-writer semantics are acceptable.

  • You can reason about plain objects as string-keyed maps.
  • You can open Try-it labs or run snippets locally.

Overview

_.keyBy is the ergonomic finish line when an API hands you an array but your UI wants records[id] access patterns.

Lookup tables

O(1) reads after one linear preprocessing pass.

Collisions expected

Treat duplicates as last-write wins unless you normalize upstream.

Iteratee shorthand

Property strings and paths behave like sibling Lodash helpers.

Syntax

javascript
_.keyBy(collection, iteratee)
  • collection: array, array-like, or plain object Lodash can iterate.
  • iteratee: invoked as (value, index|key, collection); its string-coerced result becomes the object key.
  • Returns: plain object mapping keys to a single element each.
1

Index rows by id

Shorthand property iteratees pluck the stable identifier from each record.

javascript
import keyBy from "lodash/keyBy";

keyBy(
  [
    { id: "a", score: 10 },
    { id: "b", score: 20 }
  ],
  "id"
);
// → { a: { id: "a", score: 10 }, b: { id: "b", score: 20 } }
Try it Yourself
2

Key strings by length

Duplicate lengths collide—here only one word survives per length bucket.

javascript
import keyBy from "lodash/keyBy";

keyBy(["apple", "pie", "banana"], (word) => word.length);
// → { "5": "apple", "3": "pie", "6": "banana" }
Try it Yourself
3

Duplicate keys keep the last row

Two records share slot: 1—trace which survivor lands in the map.

javascript
import keyBy from "lodash/keyBy";

keyBy(
  [
    { slot: 1, label: "first" },
    { slot: 1, label: "second" }
  ],
  "slot"
);
// → { "1": { slot: 1, label: "second" } }
Try it Yourself

📋 _.keyBy vs groupBy, map, reduce

APIShapeBest when
_.keyBy(collection, iteratee)Keys → single elementUnique-ish identifiers with defined overwrite rules
_.groupBy(collection, iteratee)Keys → arraysYou must retain every duplicate row
_.map(collection, iteratee)Array (same length)Transform elements without building a dictionary
_.reduce(collection, fn, {})Custom accumulatorAggregation logic beyond a simple key extract

Pitfalls to avoid

Dupes

Silent data loss

Audit pipelines when upstream uniqueness is not enforced—reach for groupBy or validations.

Keys

Coercion surprises

Objects used as keys stringify—distinct objects may collide once coerced.

Order

Which duplicate wins?

Documentation treats later iterations as authoritative—snapshot fixtures when auditing merges.

❓ FAQ

No—it allocates a new plain object keyed by iteratee results.
The later row overwrites the earlier one—design duplicate handling explicitly when order matters.
groupBy collects arrays per bucket; keyBy collapses to a single element per bucket.
Yes—Lodash iterates enumerable entries like other collection helpers.
Conceptually similar—keyBy is the terse built-in for this lookup-table shape.

Summary

Did you know?

Like _.groupBy, result keys come from string-coerced iteratee output—but _.keyBy keeps only one element per key (the last encountered wins).

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful