JavaScript: Reverse Object Key/Value

By Xah Lee. Date: . Last updated: .

Here is a function that reverse the key/value of object.

That is, value become key, vice versa.

/* [
xah_reverse_obj_key_val(xObj) return a new object that has its key and value reversed. If values are not unique, the previous is overwritten.
Only enumerable key and string key counts.
2018-06-04
] */
const xah_reverse_obj_key_val = ((xObj) => {
  const newObj = {};
  Object.keys(xObj).forEach((x) => {
    newObj[xObj[x]] = x;
  });
  return newObj;
});

// ssss---------------------------------------------------
// test

const xx = { a: 1, b: 2 };

console.log(xah_reverse_obj_key_val(xx));
// { "1": "a", "2": "b" }

JavaScript Reverse Key/Value

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc