Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

fromPairs

Converts an array of [key, value] pairs into an object.

TypeScript
Copied!
1/**
2 * Converts an array of [key, value] pairs into an object.
3 *
4 * @param pairs - An array of [key, value] tuples.
5 * @returns An object constructed from the given pairs.
6 */
7export function fromPairs<T>(pairs: [string, T][]): Record<string, T> {
8  return pairs.reduce((acc, [key, value]) => {
9    acc[key] = value;
10    return acc;
11  }, {} as Record<string, T>);
12}
  • Straightforward Tuple-to-Object Conversion

    Converts an array of [key, value] pairs into a plain object, mirroring native Object.fromEntries behavior with TypeScript type safety.

  • Compact and Efficient

    Uses a simple reduce for fast performance and easy-to-read implementation.

  • Supports Arbitrary Value Types

    Generic design allows any value type, making it versatile for various use cases.

  • Deterministic Behavior

    Later pairs with the same key override earlier ones, ensuring predictable key resolution.

Tests | Examples

TypeScript
Copied!
1test('fromPairs - converts pairs to object', () => {
2  const input: [string, number][] = [['a', 1], ['b', 2]];
3  expect(fromPairs(input)).toEqual({ a: 1, b: 2 });
4});
5
6test('fromPairs - handles empty input', () => {
7  expect(fromPairs([])).toEqual({});
8});
9
10test('fromPairs - overwrites duplicate keys with last value', () => {
11  const input: [string, string][] = [['a', 'x'], ['a', 'y']];
12  expect(fromPairs(input)).toEqual({ a: 'y' });
13});
14
15test('fromPairs - works with mixed value types', () => {
16  const input: [string, any][] = [['a', 1], ['b', 'hello'], ['c', true]];
17  expect(fromPairs(input)).toEqual({ a: 1, b: 'hello', c: true });
18});
19
20test('fromPairs - original array is not mutated', () => {
21  const input: [string, number][] = [['a', 1], ['b', 2]];
22  const clone = [...input];
23  fromPairs(input);
24  expect(input).toEqual(clone);
25});

Common Use Cases

  • Deserialization or Transformation

    Reconstruct an object from entries returned by Object.entries, Map, or similar sources.

  • Data Conversion Pipelines

    Convert tabular or row-based data into structured object form.

  • Building Objects Dynamically

    Programmatically assemble objects based on user input, form entries, or computed key-value pairs.

  • Filtering + Reconstruction

    Combine with Object.entries() and filter() to remove properties, then rebuild the object.

  • Utility Interop

    Support scenarios where intermediate steps require data in pair format for sorting, filtering, or mapping.

Codebase: Utilities -> Objects -> fromPairs | Yevhen Klymentiev