Skip to main content

toPairs()

toPairs<T>(object): [keyof T, T[keyof T]][]

toPairs(object): []

toPairs(object): [string, unknown][]

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

๐Ÿ’Ž Why is this a Hidden Gem?

Unlock object iteration with a clean [key, value] tuple format.

DEPRECATED

Use Object.entries() directly instead.


Type Parametersโ€‹

T: T extends Record<string, unknown>โ€‹

The type of the object.


Parametersโ€‹

Overload 1:

object: Tโ€‹

The object to convert to pairs.

Overload 2:

object: null | undefinedโ€‹

The object to convert to pairs.

Overload 3:

object: unknownโ€‹

The object to convert to pairs.


Returns: [keyof T, T[keyof T]][]โ€‹

An array of key-value pairs.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

objectEntries (Antfu) ยท toEntries (Effect) ยท toPairs (Lodash, es-toolkit, Remeda, Ramda) ยท โŒ (Radashi, Modern Dash)


Exampleโ€‹

const obj = { a: 1, b: 2, c: 3 };

// โŒ Deprecated approach
const pairs = toPairs(obj);
console.log(pairs); // [['a', 1], ['b', 2], ['c', 3]]

// โœ… Recommended approach
const nativePairs = Object.entries(obj);
console.log(nativePairs); // [['a', 1], ['b', 2], ['c', 3]]

How it works?โ€‹

Creates an array of key-value pairs. Deprecated: Use Object.entries() directly (ES2017).

Native Equivalentโ€‹

// โŒ toPairs(obj)
// โœ… Object.entries(obj)

Use Casesโ€‹

Convert to entries ๐Ÿ“Œโ€‹

Convert object to array of key-value pairs.

Object.entries({ a: 1, b: 2 });
// [['a', 1], ['b', 2]]

Transform and rebuildโ€‹

Transform object via entries.

const doubled = Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, v * 2])
);