🗝️ Indexes an array by a key, giving one element per key.

Info

This is the one-to-one counterpart of groupBy. groupBy collects every match into an array; keyBy keeps a single element, which is the shape you want for a lookup table.

Syntax

TypeScript
import { keyBy } from '@opentf/std';
keyBy<T>(
  arr: T[],
  by: ((val: T, index: number, arr: T[]) => string) | string,
): Record<string, T>;

Parameters

NameTypeDescription
arrT[]The source array.
byFunction | stringThe iteratee, or the name of a property to read.

Returns

An object mapping each key to a single element. Keys are coerced to strings.

Warning

When two elements produce the same key the later one wins. Pass a list already ordered oldest-first to keep the newest.

Warning

A key of __proto__, constructor or prototype is refused and its element dropped. The lookup is built from data, so writing one of those would make the element the prototype of the table rather than an entry in it.

Examples

TypeScript
const users = [
  { id: 'a1', name: 'Ada' },
  { id: 'b2', name: 'Linus' },
];

keyBy(users, 'id');
//=> { a1: { id: 'a1', name: 'Ada' }, b2: { id: 'b2', name: 'Linus' } }

With an iteratee:

TypeScript
keyBy(users, (u) => u.name.toLowerCase());
//=> { ada: {...}, linus: {...} }

keyBy([6.1, 4.2], Math.floor); //=> { '4': 4.2, '6': 6.1 }

Compared with groupBy:

TypeScript
groupBy(users, 'id'); //=> { a1: [ {...} ] }   ← arrays
keyBy(users, 'id');   //=> { a1: {...} }       ← single elements

Try it

Last updated on
Edit this page