arrayToHash
Converts an array of objects into a hash map (plain object) keyed by a specified property. Useful for fast lookups by a unique identifier.
Import
Section titled “Import”import { arrayToHash } from "1o1-utils";import { arrayToHash } from "1o1-utils/array-to-hash";Signature
Section titled “Signature”function arrayToHash<T>({ array, key }: ArrayToHashParams<T>): Record<string, T>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| array | T[] | Yes | The array of objects to convert |
| key | keyof T | Yes | The property to use as hash key |
Returns
Section titled “Returns”Record<string, T> — An object keyed by the specified property.
Examples
Section titled “Examples”const users = [ { id: "a1", name: "Alice" }, { id: "b2", name: "Bob" },];
arrayToHash({ array: users, key: "id" });// => { a1: { id: "a1", name: "Alice" }, b2: { id: "b2", name: "Bob" } }Edge Cases
Section titled “Edge Cases”- Throws if
arrayis not an array. - Throws if
keyis not a string. - Skips items where the key value is falsy or not a string.
Also known as
Section titled “Also known as”array to object, keyBy, objectify, index by, lookup table, dictionary
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use arrayToHash to create a lookup table from an API response array