How Lodash invert Swaps Object Keys and Values
The _.invert method in the Lodash JavaScript library
provides a simple utility for transposing the keys and values of an
object. This article breaks down how _.invert works under
the hood, demonstrates its syntax with standard code examples, explains
how it handles duplicate values and type coercion, and contrasts it with
related Lodash functions like _.invertBy.
Understanding the Core Mechanism
At its core, _.invert creates a new object where the
values of the input object become the keys, and the corresponding keys
become the values.
The underlying algorithm follows these steps:
- It initializes an empty object to store the inverted result.
- It iterates over the original object’s own enumerable string-keyed
properties using an internal iterator (similar to
Object.keys()orfor...in). - For each key-value pair, it converts the original value into a string so it can serve as an object property key.
- It assigns the original key as the value for that newly created key on the result object.
- It returns the newly constructed object, leaving the original object unmodified.
Basic Usage
Here is a straightforward implementation of
_.invert:
const _ = require('lodash');
const roleMap = {
admin: '1',
editor: '2',
viewer: '3'
};
const invertedMap = _.invert(roleMap);
console.log(invertedMap);
// Output: { '1': 'admin', '2': 'editor', '3': 'viewer' }In this example, the numeric strings '1',
'2', and '3' become the keys, and their
corresponding role names become the values.
Handling Duplicate Values
JavaScript object keys must be unique. When an input object contains
duplicate values across different keys, _.invert cannot map
multiple keys to identical property names in the resulting object.
Instead, it processes properties in iteration order, meaning subsequent values will overwrite earlier ones:
const fruits = {
a: 'apple',
b: 'banana',
c: 'apple'
};
const invertedFruits = _.invert(fruits);
console.log(invertedFruits);
// Output: { apple: 'c', banana: 'b' }Because 'c' also has the value 'apple' and
appears later in the property traversal, 'c' overwrites
'a'.
Type Coercion of Keys
Object keys in JavaScript are either strings or symbols. When
_.invert runs, any non-string value being shifted to a key
position is coerced to a string via JavaScript's standard string
conversion rules:
const mixedData = {
first: 100,
second: true,
third: null
};
const invertedData = _.invert(mixedData);
console.log(invertedData);
// Output: { '100': 'first', 'true': 'second', 'null': 'third' }Numbers, booleans, and null values are all converted
into string keys ("100", "true", and
"null").
Preserving Duplicates with
_.invertBy
If an object contains duplicate values and overwriting keys is not
desirable, Lodash provides _.invertBy. This function groups
keys corresponding to the same value into arrays rather than overwriting
them:
const statusCodes = {
badRequest: 400,
unauthorized: 401,
forbidden: 403,
notFound: 404,
customNotFound: 404
};
const groupedInvert = _.invertBy(statusCodes);
console.log(groupedInvert);
// Output:
// {
// '400': ['badRequest'],
// '401': ['unauthorized'],
// '403': ['forbidden'],
// '404': ['notFound', 'customNotFound']
// }Summary
_.invert acts as an immutable dictionary reversal tool.
It extracts each entry, casts the value into a valid property key, pairs
it with the original key, and builds a new lookup structure suitable for
bidirectional mapping or reverse lookups.