JS: Reverse Object Key/Value

By Xah Lee. Date: .

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

That is, value become key, vice versa.

/* [
xah_reverse_obj_key_val(obj) return a new obj 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 = ((obj) => {
    const newObj = {};
    Object.keys ( obj ). forEach ( (x => { newObj[obj[x]] = x }));
    return newObj;
});

JavaScript Reverse Key/Value

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc