Revert an object with Javascript
Problem
Let’s say you have a javascript object like:
const countryCodes = {
'United States': 'US',
'Canada': 'CA',
'Mexico': 'MX',
};
And you want to invert the keys and values to get the reverse object:
const codeCountries = {
'US': 'United States',
'CA': 'Canada',
'MX': 'Mexico'
};
Solution
Here’s a simple function to do that:
function revertObject(obj) {
return Object.fromEntries(
Object.entries(obj).map(a => a.reverse())
)
}
Explanation
How it works:
- The
Object.entries(obj)
method converts the object into an array of key-value pairs
[["United States","US"],["Canada","CA"],["Mexico","MX"]]
- The
map(a => a.reverse())
function then reverses each key-value pair
[["US","United States"],["CA","Canada"],["MX","Mexico"]]
Object.fromEntries()
converts the array of reversed pairs back into an object
{
'US': 'United States',
'CA': 'Canada',
'MX': 'Mexico'
};