Lodash _.keyBy() method
What you’ll learn
- How
_.keyBy(collection, iteratee)builds lookup maps from rows. - Why collisions overwrite—and how that differs from
groupByarrays. - 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
_.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.
Index rows by id
Shorthand property iteratees pluck the stable identifier from each record.
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 } } Key strings by length
Duplicate lengths collide—here only one word survives per length bucket.
import keyBy from "lodash/keyBy";
keyBy(["apple", "pie", "banana"], (word) => word.length);
// → { "5": "apple", "3": "pie", "6": "banana" } Duplicate keys keep the last row
Two records share slot: 1—trace which survivor lands in the map.
import keyBy from "lodash/keyBy";
keyBy(
[
{ slot: 1, label: "first" },
{ slot: 1, label: "second" }
],
"slot"
);
// → { "1": { slot: 1, label: "second" } } 📋 _.keyBy vs groupBy, map, reduce
| API | Shape | Best when |
|---|---|---|
_.keyBy(collection, iteratee) | Keys → single element | Unique-ish identifiers with defined overwrite rules |
_.groupBy(collection, iteratee) | Keys → arrays | You must retain every duplicate row |
_.map(collection, iteratee) | Array (same length) | Transform elements without building a dictionary |
_.reduce(collection, fn, {}) | Custom accumulator | Aggregation logic beyond a simple key extract |
Pitfalls to avoid
Silent data loss
Audit pipelines when upstream uniqueness is not enforced—reach for groupBy or validations.
Coercion surprises
Objects used as keys stringify—distinct objects may collide once coerced.
Which duplicate wins?
Documentation treats later iterations as authoritative—snapshot fixtures when auditing merges.
❓ FAQ
Summary
- Purpose:
_.keyBy(collection, iteratee)indexes elements by an iteratee-derived key. - Contrast: prefer
groupBywhen every duplicate row must remain grouped. - Next: Lodash _.map(), Lodash _.invokeMap() (previous), or collection hub.
Like _.groupBy, result keys come from string-coerced iteratee output—but _.keyBy keeps only one element per key (the last encountered wins).
6 people found this page helpful
