Lodash fromPairs: Convert Arrays to Objects

The Lodash library provides a wide range of utility functions to manipulate collections, with _.fromPairs being specifically designed for structural transformation. This article explains the exact data structure that _.fromPairs converts into a JavaScript object, how the function processes elements, and how it compares to native JavaScript alternatives.

The Input Data Structure

The _.fromPairs function converts a two-dimensional array of key-value pairs—frequently referred to as an array of pairs, entries, or two-element tuples—into a standard JavaScript object.

In this structure:

Structure Example

[
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]

How It Works in Practice

When _.fromPairs processes this nested array, it iterates through the outer list, extracts the first two elements of each sub-array, and assigns them as property-value pairs on a newly created object.

const _ = require('lodash');

const entries = [
  ['id', 101],
  ['username', 'johndoe'],
  ['isActive', true]
];

const userObject = _.fromPairs(entries);

console.log(userObject);
// Output: { id: 101, username: 'johndoe', isActive: true }

Handling Duplicates and Irregular Inputs

Native Alternative

In modern JavaScript (ES2019 and later), this transformation can be achieved natively using Object.fromEntries(), which accepts the same nested array data structure without requiring an external library dependency.