Lodash _.keyBy() method creates an object composed of keys generated from the results of running each element of collection through iterate. 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.
- iterate : (Function) parameter holds the iterate to transform keys.
Return Value: This method returns the composed aggregate object.
Example 1: In this example we use Lodash’s _.keyBy() method to transform the array into an object, keyed by the dir property.
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: In this example we use Lodash’s _.keyBy() method to create an object from the array, where keys are derived from converting the code property to characters
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 } }Lodash _.keyBy() Method – FAQs
Can _.keyBy() handle duplicate keys in Lodash?
If the iteratee produces duplicate keys, _.keyBy() keeps the last occurrence of each key, overwriting previous values.
What types of iteratees can be used with _.keyBy()?
_.keyBy() accepts functions, property names, or values as iteratees to generate keys for the object.
How does _.keyBy() handle empty collections?
If the collection is empty, _.keyBy() returns an empty object since there are no elements to generate keys.
Can _.keyBy() be used with objects in Lodash?
Yes, though typically used with arrays, _.keyBy() can also process objects, treating each value as an element to generate keys.
What happens if _.keyBy() is used without an iteratee?
If no iteratee is provided, _.keyBy() defaults to using _.identity, which means each element itself will be used as the key.