JS: Swap Object Key Value 📜

By Xah Lee. Date: . Last updated: .

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

That is, value become key, vice versa.

/*
xah_swap_obj_key_val(xObj)
return a new object that has its key and value swapped.
If values are not unique, the previous is overwritten.
Only enumerable key and string key counts.
URL http://xahlee.info/js/js_reverse_obj_key_val.html
Created: 2018-06-04
Version: 2023-10-11
*/
const xah_swap_obj_key_val = (xObj) => {
 const xnew = {};
 Object.keys(xObj).forEach((x) => {
  xnew[xObj[x]] = x;
 });
 return xnew;
};

// s------------------------------
// test

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

console.log(JSON.stringify(xah_swap_obj_key_val(xx)) === '{"1":"a","2":"b"}');

JavaScript. Reverse Key Value