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:
- The outer container must be an
Array. - Each item inside the outer array must be an array where the first element represents the object property key and the second element represents the corresponding value.
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
- Duplicate Keys: If the input array contains sub-arrays with the same key, subsequent occurrences will overwrite earlier ones, matching standard JavaScript object behavior.
- Non-String Keys: Any non-string primitive used as a key in the first position is automatically coerced to a string or Symbol according to standard JavaScript object key rules.
- Length of Sub-arrays: If an inner array contains
more than two items, elements beyond the second index are ignored. If an
inner array contains only one item, the key is set and its value becomes
undefined.
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.