Skip to content

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 { arrayToHash } from "1o1-utils";
import { arrayToHash } from "1o1-utils/array-to-hash";
function arrayToHash<T>({ array, key }: ArrayToHashParams<T>): Record<string, T>
NameTypeRequiredDescription
arrayT[]YesThe array of objects to convert
keykeyof TYesThe property to use as hash key

Record<string, T> — An object keyed by the specified property.

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" } }
  • Throws if array is not an array.
  • Throws if key is not a string.
  • Skips items where the key value is falsy or not a string.

array to object, keyBy, objectify, index by, lookup table, dictionary

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