how to use the indexby function from the underscore library in javascript

The _.indexBy(list, iteratee) function from the Underscore library in Javascript creates an object composed of keys generated from the results of running each element of list through an iteratee function.

The code below demonstrates how to use _.indexBy() function with an array of objects:

index.tsx
const _ = require('underscore');

const persons = [
  {name: 'John', age: 28},
  {name: 'Alice', age: 32},
  {name: 'Bob', age: 24},
  {name: 'Charlie', age: 30}
];

const personsIndex = _.indexBy(persons, 'name');
// Output: 
// {
//   "John": {name: "John", age: 28},
//   "Alice": {name: "Alice", age: 32},
//   "Bob": {name: "Bob", age: 24},
//   "Charlie": {name: "Charlie", age: 30}
// }
394 chars
18 lines

In the example above, the persons array is indexed by the name property of each object using the _.indexBy() function. The resulting object has keys generated from each person's name and values that are the corresponding person object.

gistlibby LogSnag