Skip to main content

fromPairs()

fromPairs<Key, Value>(pairs): Record<Key, Value>

Creates an object from an array of key-value pairs.

๐Ÿ’Ž Why is this a Hidden Gem?

Transform key-value tuples into fully typed objects in a single call.

DEPRECATED

Use Object.fromEntries(pairs) directly instead.

Reason:
Native equivalent method now available


Type Parametersโ€‹

Key: Key extends PropertyKeyโ€‹

The type of object keys.

Value: Valueโ€‹

The type of object values.


Parametersโ€‹

pairs: [Key, Value][]โ€‹

The key-value pairs.


Returns: Record<Key, Value>โ€‹

A new object composed from the key-value pairs.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

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


Exampleโ€‹

const pairs: [string, number][] = [['a', 1], ['b', 2], ['c', 3]];

// โŒ Deprecated approach
const obj = fromPairs(pairs);
console.log(obj); // { a: 1, b: 2, c: 3 }

// โœ… Recommended approach
const objNative = Object.fromEntries(pairs);
console.log(objNative); // { a: 1, b: 2, c: 3 }

How it works?โ€‹

Creates an object from key-value pairs. Deprecated: Use Object.fromEntries() directly (ES2019).

Native Equivalentโ€‹

// โŒ fromPairs(pairs)
// โœ… Object.fromEntries(pairs)

Use Casesโ€‹

Convert entries to object ๐Ÿ“Œโ€‹

Create an object from key-value pairs.

const pairs = [["a", 1], ["b", 2], ["c", 3]];
Object.fromEntries(pairs);
// => { a: 1, b: 2, c: 3 }

Build config from arrayโ€‹

Transform configuration arrays into objects.

const config = [["host", "localhost"], ["port", 3000]];
Object.fromEntries(config);
// => { host: "localhost", port: 3000 }

Convert Map to objectโ€‹

Transform a Map into a plain object.

const map = new Map([["key1", "value1"], ["key2", "value2"]]);
Object.fromEntries(map);
// => { key1: "value1", key2: "value2" }

Build query params from active filtersโ€‹

Construct a query parameter object from a list of active filter selections. Common in search UIs where filters are toggled on/off dynamically.

const activeFilters = [
{ key: "category", value: "electronics" },
{ key: "minPrice", value: "50" },
{ key: "inStock", value: "true" },
];

const queryParams = fromPairs(activeFilters.map((f) => [f.key, f.value]));
// => { category: "electronics", minPrice: "50", inStock: "true" }

const url = `/api/products?${new URLSearchParams(queryParams)}`;
// => "/api/products?category=electronics&minPrice=50&inStock=true"