Borislav Hadzhiev
Mon Nov 22 2021·3 min read
Photo by Jason Blackeye
To swap the keys and values in an object, call the Object.entries()
method
to get an array of key-value pairs and use the map()
method to switch the
places of the key and the value. Pass the result to the Object.fromEntries()
method to get an object with swapped keys and values.
function swapKeysAndValues(obj) { // 👇️ [['color', 'blue'], ['fruit', 'apple']] const swapped = Object.entries(obj).map( ([key, value]) => [value, key] ); return Object.fromEntries(swapped); } // 👇️ {color: 'blue', fruit: 'apple'} console.log( swapKeysAndValues({blue: 'color', apple: 'fruit'}) );
The first step is to use the Object.entries method to get an array of the object's key-value pairs.
// 👇️ [['blue', 'color'], ['apple', 'fruit']] console.log(Object.entries({blue: 'color', apple: 'fruit'}))
We use the Array.map method to swap the places of the key and the value in the arrays.
The function we passed to the map()
method gets called with each element
(sub-array) in the array.
We use destructuring assignment to get the first and second elements of each sub-array.
const [key, value] = ['color', 'blue']; console.log(key); // 👉️ "color" console.log(value); // 👉️ "blue"
We simply switch the order of the key and value and return a new array containing the result.
The final value the swapped
variable contains is an array of arrays, where the
values are at index 0
and the keys - at index 1
.
The last step is to pass the array to the Object.fromEntries method.
The Object.fromEntries
method takes an array of key-value pairs, adds them to
an object and returns the result.
// 👇️ {blue: 'color', apple: 'fruit'} console.log( Object.fromEntries([ ['blue', 'color'], ['apple', 'fruit'], ]), );
We swap the keys and the values of an object in 3 steps:
Object.entries()
method.map()
method to swap the place of each key and value.Object.fromEntries()
method to transform the key-value pair arrays
to an object.An alternative approach is to return an array of objects from the map()
method.
function swapKeysAndValues(obj) { // 👇️ [{color: 'blue'}, {fruit: 'apple'}] const swapped = Object.entries(obj).map( ([key, value]) => ({[value]: key}) ); return Object.assign({}, ...swapped); } // 👇️ {color: 'blue', fruit: 'apple'} console.log(swapKeysAndValues({blue: 'color', apple: 'fruit'}));
In this example, we return an array of objects from the map()
method. Again,
we switch the key and the value for each pair.
This allows us to use the Object.assign method to copy the properties of all objects to a single object.
Object.assign
method.The first parameter the Object.assign
method takes is a target object, and
the next - source object(s). The key-value pairs of the source objects get
copied to the target object.
Object.assign
approach because two dimensional arrays are a bit of a mind bender.