Lodash _.keyBy() Method
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.keyBy() method creates an object that composed of keys generated from the results of running an each element of collection through iteratee. Corresponding value of each key is the last element that responsible for generating the key.
Syntax:
_.keyBy( collection, iteratee )
Parameters: This method accepts two parameters as mentioned above and described below:
- collection: This parameter holds the collection to iterate over.
- iteratee: This parameter holds the iteratee to transform keys.
Return Value: This method returns the composed aggregate object.
Example 1:
// Requiring the lodash library const _ = require( "lodash" ); // Original array var 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:
// Requiring the lodash library const _ = require( "lodash" ); // Original array var 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 } }
Please Login to comment...