Lodash _.keyBy() Method
Last Updated :
18 Oct, 2023
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
const _ = require( "lodash" );
let array = [
{ 'dir' : 'left' , 'code' : 89 },
{ 'dir' : 'right' , 'code' : 71 }
];
let keyby_array = _.keyBy(array, 'dir' );
console.log(keyby_array);
|
Output:
{ 'left': { 'dir': 'left', 'code': 89 },
'right': { 'dir': 'right', 'code': 71 } }
Example 2:
javascript
const _ = require( "lodash" );
let array = [
{ 'dir' : 'left' , 'code' : 89 },
{ 'dir' : 'right' , 'code' : 71 }
];
let keyby_array = _.keyBy(array, function (o) {
return String.fromCharCode(o.code);
});
console.log(keyby_array);
|
Output:
{ 'Y': { 'dir': 'left', 'code': 89 },
'G': { 'dir': 'right', 'code': 71 } }
Share your thoughts in the comments
Please Login to comment...