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:

  1. Filtering for Own Enumerable Properties: Lodash iterates only through the object's own properties, ignoring properties inherited through the prototype chain.
  2. String Key Normalization: All property keys are extracted as strings, ensuring consistent indexing within the output pairs.
  3. 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:

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:

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.