How to swap key with value in object with JavaScript?

Sometimes, we want to swap key with value in object with JavaScript.

In this article, we’ll look at how to swap key with value in object with JavaScript.

How to swap key with value in object with JavaScript?

To swap key with value in object with JavaScript, we can us the Object.entries and Object.fromEntries methods.

For instance, we write

const f = (obj) =>
  Object.fromEntries(Object.entries(obj).map((a) => a.reverse()));

to call Object.entries to return an array of key-value pair arrays.

Then we call map with a callback to reverse the key and value in each nested array with reverse.

Next, we convert the mapped nested array back to an object with Object.fromEntries.

Conclusion

To swap key with value in object with JavaScript, we can us the Object.entries and Object.fromEntries methods.