How to Swap the Keys and Values of an Object in JavaScript
A common data transformation task is to "invert" an object, swapping its keys and values. For example, you might want to turn an object like { id: 'name' } into a reverse lookup table like { name: 'id' }.
This guide will demonstrate the modern, declarative, and recommended best practice for this task using Object.entries(), map(), and Object.fromEntries(). We will also cover the most critical pitfall of this operation: the risk of data loss when your object has duplicate values.
The Core Problem: Data Loss from Duplicate Values
This is the most important concept to understand before you swap an object's keys and values. Object keys must be unique. If your original object has multiple keys that share the same value, only one of them will survive the swap, leading to silent data loss.
Example of problem:
// Problem: The value 'Admin' appears twice.
const userRoles = {
alice: 'Admin',
bob: 'Editor',
charlie: 'Admin',
};
When we swap this, "Admin" will become a key. Since an object can only have one "Admin" key, one of the original keys (alice or charlie) will be overwritten.
The standard behavior is that the last key encountered wins.
alice: 'Admin'is processed first. The new object is{ Admin: 'alice', ... }.charlie: 'Admin'is processed later. It overwrites the existingAdminkey. The new object becomes{ Admin: 'charlie', ... }.
You must be certain that the values in your source object are unique before performing a swap if you want to avoid data loss.
The Core Method (Recommended): Object.fromEntries() and map()
This modern, functional approach is the cleanest and most readable way to invert an object.
The logic:
- Convert: Convert the object into an array of
[key, value]pairs usingObject.entries(). - Swap: Use
Array.prototype.map()to create a new array where each[key, value]pair is swapped to[value, key]. - Reconstruct: Convert the new array of swapped pairs back into an object using
Object.fromEntries().
Solution:
function swapKeysAndValues(obj) {
const entries = Object.entries(obj);
const swappedEntries = entries.map(([key, value]) => [value, key]);
return Object.fromEntries(swappedEntries);
}
// Example Usage (with unique values):
const originalObject = {
color: 'blue',
fruit: 'apple',
animal: 'dog'
};
const swappedObject = swapKeysAndValues(originalObject);
console.log(swappedObject);
Output:
{ blue: 'color', apple: 'fruit', dog: 'animal' }
This can also be written as a concise one-liner:
const swappedObject = Object.fromEntries(
Object.entries(originalObject).map(([key, value]) => [value, key])
);
How the Method Works
Let's break down the process step-by-step.
Step 1: Convert the Object to an Array of Entries
Object.entries(obj) transforms the object into an array of its [key, value] pairs.
const obj = { color: 'blue', fruit: 'apple' };
const entries = Object.entries(obj);
// entries is now [ ['color', 'blue'], ['fruit', 'apple'] ]
Step 2: Map Over the Entries to Swap Each Pair
We use map() to create a new array. For each [key, value] pair, we return a new array with the elements flipped: [value, key]. Destructuring assignment ([key, value]) makes this clean.
const swappedEntries = entries.map(([key, value]) => [value, key]);
// swappedEntries is now [ ['blue', 'color'], ['apple', 'fruit'] ]
Step 3: Convert the Array of Entries Back to an Object
Object.fromEntries() takes an array of [key, value] pairs and creates a new object from them.
const finalObject = Object.fromEntries(swappedEntries);
// finalObject is now { blue: 'color', apple: 'fruit' }
An Alternative Method: Using reduce()
A more traditional functional approach is to use Array.prototype.reduce() to build the new object. This is also a valid method, though it can be less readable for developers unfamiliar with reduce.
const originalObject = { color: 'blue', fruit: 'apple' };
const swappedObject = Object.entries(originalObject).reduce((acc, [key, value]) => {
acc[value] = key;
return acc;
}, {}); // Start with an empty object
console.log(swappedObject); // Output: { blue: 'color', apple: 'fruit' }
Practical Example: Creating a Reverse Lookup Map
A great use case for swapping keys and values is to create a reverse lookup object.
const statusCodes = {
'OK': 200,
'Created': 201,
'Not Found': 404,
'Internal Server Error': 500
};
// We want to be able to look up the name from the code.
const codeToNameMap = Object.fromEntries(
Object.entries(statusCodes).map(([key, value]) => [value, key])
);
console.log(codeToNameMap);
// Output: { '200': 'OK', '201': 'Created', '404': 'Not Found', '500': 'Internal Server Error' }
console.log(codeToNameMap[404]);
// Output: "Not Found"
The numeric values are coerced to strings when they become object keys.
Conclusion
Swapping the keys and values of a JavaScript object is a simple data transformation with a clear, modern solution.
- The recommended best practice is the three-step process:
Object.entries(), thenmap()to swap the pairs, and finallyObject.fromEntries()to reconstruct the object. - Crucially, be aware of data loss. If your original object has duplicate values, only the last key associated with that value will be kept after the swap.
- The
reduce()method is a valid and powerful alternative, but theObject.fromEntries()approach is often considered more declarative and readable.