How Lodash fromPairs Handles Duplicate Keys

The _.fromPairs function in the Lodash JavaScript library constructs an object from an array of key-value pairs. When duplicate keys exist in the input array, the function uses a "last write wins" strategy, meaning any subsequent value assigned to a repeated key will overwrite its previous value. This article explains the internal mechanics of this behavior, provides clear code examples, and offers alternatives for situations where data from duplicate keys must be preserved.

The "Last Write Wins" Mechanism

The _.fromPairs method processes the input array sequentially from the first element to the last. Internally, it iterates through each pair and assigns the value to the object using standard JavaScript property assignment:

result[pair[0]] = pair[1];

Because property assignments on plain JavaScript objects overwrite existing values for identical keys, any subsequent pair with an existing key replaces whatever value was previously stored.

Code Example

Consider an array containing duplicate entries for the key 'user':

const _ = require('lodash');

const pairs = [
  ['id', 1],
  ['user', 'Alice'],
  ['role', 'Admin'],
  ['user', 'Bob'] // Duplicate key
];

const result = _.fromPairs(pairs);

console.log(result);
// Output:
// { id: 1, user: 'Bob', role: 'Admin' }

In this example, the initial assignment sets result.user = 'Alice'. When the iterator reaches the final pair, it sets result.user = 'Bob'. The final object retains 'Bob', completely discarding 'Alice'.

Key Conversion Behavior

JavaScript object keys are always strings or symbols. If duplicate keys are supplied in formats that evaluate to the same string representation, _.fromPairs treats them as the exact same key:

const pairs = [
  [1, 'numeric one'],
  ['1', 'string one']
];

console.log(_.fromPairs(pairs));
// Output: { '1': 'string one' }

Even though the first key is a number and the second is a string, JavaScript normalizes numeric keys to strings during assignment, leading to an overwrite.

Preserving Duplicate Values

If your dataset contains duplicate keys and you need to keep all associated values rather than discarding earlier entries, _.fromPairs is not the appropriate tool.

Grouping Values with Array.prototype.reduce

You can use a custom reducer to aggregate all duplicate values into an array:

const pairs = [
  ['tag', 'javascript'],
  ['tag', 'lodash'],
  ['tag', 'web']
];

const grouped = pairs.reduce((acc, [key, value]) => {
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(value);
  return acc;
}, {});

console.log(grouped);
// Output: { tag: ['javascript', 'lodash', 'web'] }

Using Lodash Alternatives

You can also combine other Lodash functions, such as _.groupBy and _.mapValues, to group and extract values cleanly:

const pairs = [
  ['category', 'books'],
  ['category', 'movies'],
  ['author', 'John Doe']
];

const grouped = _.mapValues(
  _.groupBy(pairs, pair => pair[0]),
  values => values.map(pair => pair[1])
);

console.log(grouped);
// Output: { category: ['books', 'movies'], author: ['John Doe'] }

Summary

_.fromPairs is designed for simple, 1-to-1 key-value mapping. When duplicate keys are passed, it sequentially assigns each property, ensuring that the last occurrence of any key in the array defines its final value in the resulting object.