keyBy

collection

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 responsible for generating the key.

Signature

keyBy<T>(collection: T[], iteratee: ((value: T) => PropertyKey) | keyof T): Record<PropertyKey, T>

Parameters

NameTypeDescription
collectionT[]The collection to iterate over
iteratee((value: T) => PropertyKey) | keyof TThe iteratee to transform keys (can be a function or property name)

Returns

Record<PropertyKey, T> - Returns the composed aggregate object

Examples

Index by function result

import { keyBy } from 'dashlite'

const array = [
  { dir: 'left', code: 97 },
  { dir: 'right', code: 100 }
]
const result = keyBy(array, (o) => String.fromCharCode(o.code))
console.log(result)

Output:

{ 'a': { dir: 'left', code: 97 }, 'd': { dir: 'right', code: 100 } }

Index by property

import { keyBy } from 'dashlite'

const array = [
  { id: 'user1', name: 'Alice' },
  { id: 'user2', name: 'Bob' }
]
const result = keyBy(array, 'id')
console.log(result)

Output:

{ user1: {...}, user2: {...} }

Available since version 1.2.0