Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Lodash _.keyBy() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 } }

My Personal Notes arrow_drop_up
Last Updated : 07 Sep, 2020
Like Article
Save Article
Similar Reads
Related Tutorials