Swap the Keys and Values in an Object using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Swap the Keys and Values in an Object in JavaScript

To swap the keys and values in an object:

  1. Use the Object.entries() method to get an array of key-value pairs.
  2. Use the map() method to switch the places of each key and value.
  3. Use the Object.fromEntries() method to get an object with swapped keys and values.
index.js
function swapKeysAndValues(obj) { // ๐Ÿ‘‡๏ธ [['color', 'blue'], ['fruit', 'apple']] const swapped = Object.entries(obj).map( ([key, value]) => [value, key] ); return Object.fromEntries(swapped); } // ๐Ÿ‘‡๏ธ {color: 'blue', fruit: 'apple'} console.log( swapKeysAndValues({blue: 'color', apple: 'fruit'}) );

swap keys and values in object

The code for this article is available on GitHub

The Object.entries() method returns an array of the given object's key-value pairs.

index.js
// ๐Ÿ‘‡๏ธ [['blue', 'color'], ['apple', 'fruit']] console.log(Object.entries({blue: 'color', apple: 'fruit'}))
The first element in each nested array is the key, and the second is the value.

The function we passed to the Array.map() method gets called with each element in the array.

index.js
function swapKeysAndValues(obj) { // ๐Ÿ‘‡๏ธ [['color', 'blue'], ['fruit', 'apple']] const swapped = Object.entries(obj).map( ([key, value]) => [value, key] ); return Object.fromEntries(swapped); }
The code for this article is available on GitHub

The map() method returns a new array containing the values returned from the callback function.

We used destructuring assignment to get the first and second elements of each nested array.

index.js
const [key, value] = ['color', 'blue']; console.log(key); // ๐Ÿ‘‰๏ธ "color" console.log(value); // ๐Ÿ‘‰๏ธ "blue"

We simply switch the order of the key and value and return a new array containing the result.

The final value the swapped variable contains is an array of arrays, where the values are at index 0 and the keys are at index 1.

The last step is to pass the array to the Object.fromEntries() method.

The Object.fromEntries() transforms a list of key-value pairs into an object.

index.js
// ๐Ÿ‘‡๏ธ {blue: 'color', apple: 'fruit'} console.log( Object.fromEntries([ ['blue', 'color'], ['apple', 'fruit'], ]), );

Swapping the keys and values of an object is a 3-step process:

  1. Get an array of key-value pairs using the Object.entries() method.
  2. Use the map() method to swap the place of each key and value.
  3. Use the Object.fromEntries() method to transform the key-value pair arrays into an object.

# Swap the keys and values in an object using Object.assign()

An alternative approach is to return an array of objects from the map() method.

index.js
function swapKeysAndValues(obj) { // ๐Ÿ‘‡๏ธ [{color: 'blue'}, {fruit: 'apple'}] const swapped = Object.entries(obj).map( ([key, value]) => ({[value]: key}) ); return Object.assign({}, ...swapped); } // ๐Ÿ‘‡๏ธ {color: 'blue', fruit: 'apple'} console.log(swapKeysAndValues({blue: 'color', apple: 'fruit'}));

swap keys and values in object using object assign

The code for this article is available on GitHub

The callback function we passed to map() returns an array of objects with switched keys and values.

This allows us to use the Object.assign() method to copy the properties of all objects into a single object.

We used the spread syntax (...) to unpack the values (objects) from the array and passed them as arguments to the Object.assign method.

The Object.assign() method copies all of the properties from a source object to a target object.

index.js
const target = {a: 1, b: 3}; const source = {a: 2, c: 5}; const obj = Object.assign(target, source); console.log(obj); // ๐Ÿ‘‰๏ธ { a: 2, b: 3, c: 5 }

The Object.assign() method takes 2 parameters:

  1. the target object - the object to which the sources' properties are applied
  2. the sources - the source objects that contain the properties to be applied to the target object.

The method returns the target object with the provided properties applied.

# Swap the keys and values in an object using Array.forEach()

You can also use the Array.forEach() method to swap the keys and values in an object.

index.js
function swapKeysAndValues(obj) { const newObj = {}; Object.entries(obj).forEach(([key, value]) => { newObj[value] = key; }); return newObj; } // ๐Ÿ‘‡๏ธ {color: 'blue', fruit: 'apple'} console.log(swapKeysAndValues({blue: 'color', apple: 'fruit'}));

swap keys and values in object using foreach

The code for this article is available on GitHub

We first used the Object.entries() method to get an array of key-value pairs.

index.js
// ๐Ÿ‘‡๏ธ [ [ 'blue', 'color' ], [ 'apple', 'fruit' ] ] console.log(Object.entries({blue: 'color', apple: 'fruit'}));

The function we passed to the Array.forEach() method gets called with each element in the array.

On each iteration, we swap the key and value of the object.

# Swap the keys and values in an object using Array.reduce()

You can also use the Array.reduce() method to swap the keys and values in an object.

index.js
function swapKeysAndValues(obj) { return Object.entries(obj).reduce((accumulator, entry) => { const [key, value] = entry; accumulator[value] = key; return accumulator; }, {}); } // ๐Ÿ‘‡๏ธ {color: 'blue', fruit: 'apple'} console.log(swapKeysAndValues({blue: 'color', apple: 'fruit'}));

swap keys and values in object using array reduce

The code for this article is available on GitHub

We used the Object.entries() method to get an array of key-value pairs and used the reduce() method to iterate over the array.

The function we passed to the Array.reduce() method gets called for each element in the array.

We initialized the accumulator variable to an empty object because that's what we passed as the second argument to the reduce() method.

The value we return from the callback function gets passed as the accumulator on the next iteration.

On each iteration, we swap the current key-value pair and return the accumulator object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev