Builds an object whose keys come from running each element through an iteratee. The value for each key is the last element that produced that key. Use it to turn an array of rows into a fast lookup map. Part of Lodash 4.x Collection (since 4.0.0).
Pass the required arguments shown below. Lodash Collection helpers usually return a new value — check whether the source is mutated.
Syntax
Call _.keyBy on a collection. Start with this line.
Lodash
_.keyBy(collection, [iteratee=_.identity])
Call
What it does
_.keyBy(collection, [iteratee=_.identity])
Primary signature.
_.keyBy(collection)
Call with a collection argument.
Prefer import keyBy from "lodash/keyBy" when you want a smaller bundle.
_.keyBy(["apple", "pie", "banana"], function (word) {
return word.length;
});
// → { "3": "pie", "5": "apple", "6": "banana" }
// note: "apple" and any other length-5 word would collide
Order. Object key order follows insertion of unique keys.
vs groupBy.groupBy would keep arrays if lengths repeated.
Compatibility
Browser & Runtime Support
_.keyBy is a Lodash 4.x Collection helper (since 4.0.0). It runs anywhere Lodash runs — modern browsers (CDN or bundle) and Node.js / Bun / Deno with npm install lodash. Native alternatives are hand-rolled reduce / Object.fromEntries patterns.
✓ Stable · Lodash 4.0+
_.keyBy()
Available in [email protected] full builds and the lodash/keyBy modular import. Works in evergreen browsers and current Node LTS when Lodash is installed.
100%With Lodash 4.x
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
_.keyByLodash 4.0+
Bottom line: Safe for production once Lodash is loaded. Prefer import keyBy from "lodash/keyBy" for smaller builds. Use when you need one element per key for fast lookups.
Frequently Asked Questions
_.keyBy(collection, iteratee) builds a plain object. Each key comes from the iteratee; the value is the element that produced that key.
No. It returns a new object. Elements themselves are not cloned.
The last element wins — earlier rows with the same key are overwritten.
groupBy stores arrays of all matches per key. keyBy stores one element per key.
Yes. Pass a string like "id" or "dir" as the iteratee shorthand.
Object keys are string-coerced. Prefer string or number keys you expect to look up later.