Skip to main content

zipObject()

zipObject<K, V>(keys, values): Record<K, V>

Creates an object composed from arrays of keys and values.

๐Ÿ’Ž Why is this a Hidden Gem?

A concise way to create typed objects from parallel key-value arrays.

DEPRECATED

Use Object.fromEntries() with map() or zip() directly instead.


Type Parametersโ€‹

K: K extends PropertyKeyโ€‹

The type of keys (must be valid property key).

V: Vโ€‹

The type of values.


Parametersโ€‹

keys: readonly K[]โ€‹

The property keys.

values: readonly V[]โ€‹

The property values.


Returns: Record<K, V>โ€‹

The new object.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

fromEntries (Effect) ยท fromPairs (Remeda) ยท objectify (Radashi) ยท zipObj (Ramda) ยท zipObject (Lodash, es-toolkit) ยท โŒ (Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
zipObject(['a', 'b'], [1, 2]);
// => { a: 1, b: 2 }

// โœ… Recommended approach
Object.fromEntries(['a', 'b'].map((k, i) => [k, [1, 2][i]]));
// => { a: 1, b: 2 }

// Or using zip from Arkhe
import { zip } from '@pithos/arkhe/array/zip';
Object.fromEntries(zip(['a', 'b'], [1, 2]));
// => { a: 1, b: 2 }

How it works?โ€‹

Creates an object from arrays of keys and values.

Processing Flowโ€‹

Common Inputsโ€‹

KeysValuesResult
['a', 'b'][1, 2]{a: 1, b: 2}
['x', 'y', 'z'][10, 20]{x: 10, y: 20, z: undefined}

warning Deprecated: Use Object.fromEntries() with map() or zip().


Use Casesโ€‹

Create object from arrays ๐Ÿ“Œโ€‹

Create an object from arrays of keys and values.

const keys = ["a", "b", "c"];
const values = [1, 2, 3];
Object.fromEntries(keys.map((k, i) => [k, values[i]]));
// => { a: 1, b: 2, c: 3 }

Map fields to valuesโ€‹

Build an object from parallel arrays.

const fields = ["name", "email", "age"];
const data = ["Alice", "alice@example.com", 30];
Object.fromEntries(fields.map((f, i) => [f, data[i]]));
// => { name: "Alice", email: "alice@example.com", age: 30 }

Combine headers with rowโ€‹

Create object from CSV header and data row.

const headers = ["id", "title", "price"];
const row = [1, "Product", 99.99];
Object.fromEntries(headers.map((h, i) => [h, row[i]]));