Categories
JavaScript Answers

How to Swap the Keys and Values of a JavaScript Object?

Spread the love

We can use the Object.entries to get an object’s keys and values in an array of key-value pairs.

And we can use Object.fromEntries to convert an array of key-value pairs to an object.

Therefore, we can use them to swap the keys and values of an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const swapped = Object.fromEntries(Object.entries(obj).map(a => a.reverse()))
console.log(swapped)

We have the obj opbject that we want to swap the keys and values for.

To do that, we call Object.entries with obj .

Then we call map to call reverse on each entry to do the swap.

And then we call Object.fromEntries on the array returned by map to convert it back to an object.

And we get:

{1: "a", 2: "b", 3: "c"}

as the value of swapped .

We can do the same swap by using destructuring:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const swapped = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]))
console.log(swapped)

We destructure the parameter of the map callback and return the 2 items swapped.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *