VOOZH about

URL: https://www.geeksforgeeks.org/javascript/lodash-_-keyby-method/

⇱ Lodash _.keyBy() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lodash _.keyBy() Method

Last Updated : 3 Sep, 2024

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.

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

Output:

{ 'Y': { 'dir': 'left', 'code': 89 }, 
'G': { 'dir': 'right', 'code': 71 } }
Comment