Friday, September 5, 2025
HomeLanguagesJavascriptLodash _.keyBy() Method

Lodash _.keyBy() Method

Lodash _.keyBy() method creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the last element that is responsible for generating the key.

Syntax:

_.keyBy( collection, iteratee )

Parameters:

  • collection (Array|Object) parameter holds the collection to iterate over.
  • iteratee(Function) parameter holds the iteratee to transform keys.

Return Value:

This method returns the composed aggregate object.

Example 1:

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array = [
    { 'dir': 'left', 'code': 89 },
    { 'dir': 'right', 'code': 71 }
];
 
// Use of _.keyBy() method
let keyby_array = _.keyBy(array, 'dir');
 
// Printing the output
console.log(keyby_array);


Output:

{ 'left': { 'dir': 'left', 'code': 89 }, 
'right': { 'dir': 'right', 'code': 71 } }

Example 2:

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array = [
    { 'dir': 'left', 'code': 89 },
    { 'dir': 'right', 'code': 71 }
];
 
// Use of _.keyBy() method
let keyby_array = _.keyBy(array, function (o) {
    return String.fromCharCode(o.code);
});
 
// Printing the output
console.log(keyby_array);


Output:

{ 'Y': { 'dir': 'left', 'code': 89 }, 
'G': { 'dir': 'right', 'code': 71 } }
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6637 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS