Lodash toPairs: Serialize Objects into 2D Arrays
The _.toPairs method in Lodash serializes an object into
a two-dimensional array of key-value pairs, providing a dependable
utility for data transformation and object traversal in JavaScript. This
article explains how _.toPairs extracts own enumerable
string-keyed properties into tuple-like pairs, how its internal
mechanics operate, how it handles various data types and edge cases, and
how it compares to standard native JavaScript features.
Core Serialization Mechanism
At its core, _.toPairs(object) accepts a single source
object and returns an array of arrays, where each inner array contains
exactly two elements: the property name (the key) at index
0, and the corresponding property value at index
1.
const _ = require('lodash');
const user = {
id: 101,
username: 'alex_dev',
role: 'admin'
};
const result = _.toPairs(user);
// Output: [ ['id', 101], ['username', 'alex_dev'], ['role', 'admin'] ]During serialization, Lodash executes three main steps:
- Filtering for Own Enumerable Properties: Lodash iterates only through the object's own properties, ignoring properties inherited through the prototype chain.
- String Key Normalization: All property keys are extracted as strings, ensuring consistent indexing within the output pairs.
- Tuple Construction: Each key-value association is
packaged into a mini-array
[key, value]and pushed to the parent array.
Handling Edge Cases and Data Types
_.toPairs features defensive programming conventions
that prevent runtime exceptions when dealing with atypical inputs:
- Null and Undefined: Unlike native methods that
throw a
TypeErrorwhen givennullorundefined,_.toPairsfails gracefully and returns an empty array ([]). - Arrays: When passed an array,
_.toPairsserializes the array indices as string keys. For example,_.toPairs(['a', 'b'])produces[['0', 'a'], ['1', 'b']]. - Prototype Inheritance: Inherited properties are
explicitly omitted. If inherited properties need to be captured
alongside own properties, Lodash provides a separate method,
_.toPairsIn.
function Base() {
this.ownProperty = 'visible';
}
Base.prototype.inheritedProperty = 'hidden';
const instance = new Base();
console.log(_.toPairs(instance));
// Output: [ ['ownProperty', 'visible'] ]
console.log(_.toPairsIn(instance));
// Output: [ ['ownProperty', 'visible'], ['inheritedProperty', 'hidden'] ]Lodash
_.toPairs vs. Native Object.entries
Modern ECMAScript provides Object.entries(), which
performs the same serialization format as _.toPairs.
However, there are functional differences:
- Safety:
Object.entries(null)orObject.entries(undefined)causes a fatal exception._.toPairs(null)safely yields[]. - Cross-Environment Compatibility:
_.toPairsprovides a unified API for environments where ECMAScript 2017 (ES8) methods are not natively supported without polyfills.
By strictly capturing own enumerable properties and formatting them
as standard key-value tuples, _.toPairs transforms
arbitrary objects into standardized 2D arrays ready for functional
operations like mapping, filtering, or feeding into collection-based
workflows.