In this article, we will cover how to swap a JavaScript object’s keys and values. To achieve this, we will use the `Object.entries()` method to get an array of the object’s key-value pairs. Then, we will need loop over the array using the `map()` method and swap keys with values and store the output in another array.
Finally, we will use the `Object.fromEntires()` method to create an object with swapped keys and values from our generated array.
How To Swap A JavaScript Object’s Keys And Values
First, let’s create a new object and initialize it with some values –
const obj = {
key1: "value1",
key2: "value2"
};
Then, we need to create an array with our object’s key-value pairs using the `Object.entries()` method –
const keysValues = Object.entries(obj);
Let’s print the `keysValues` array on the console to check what we have –
console.log(keysValues);
Then, we need to loop over the `keysValues` array using the `map()` method and generate a new array with swapped key-value pairs.
const swappedKeysValues = keysValues.map(([key, value]) => {
[value, key];
});
Then, we will print the `swappedKeysValues` on the console to check the swapped values –
console.log(swappedKeysValues);
Finally, we need to create a new object with the swapped key-value pairs using the `Object.fromEntries()` method passing in `swappedKeysValues` array as an argument.
const swappedObj = Object.fromEntries(swappedKeysValues);
Now, if we print the `swappedObj` on the console, we will see that we have an object with swapped keys and values from the original object `obj` that we created earlier.
console.log(swappedObj);
We can wrap our logic into a function block so that we can apply it on any object we like.
const swapKeysValues = (object) => {
const keysValues = Object.entries(object);
const swappedKeysValues = keysValues.map(([key, value]) => {
return [value, key];
});
const swappedObject = Object.fromEntries(swappedKeysValues);
return swappedObject;
};
If we call our function inside a `console.log()` statement, we will get an object with the swapped keys and values from our original object.
console.log(swapKeysValues(obj));