Invert Object Keys and Values
Creates a new object by swapping keys and values of the given object.
- object
- invert
Install
npx shadcn@latest add https://quicksnip.dev/r/invert-object-keys-and-values.jsonThis snippet is not verified yet. Review it before use, or help verify it.
Code
function invertObject(obj) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [value, key])
);
}Usage
const obj = { a: 1, b: 2, c: 3 };
invertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }