JavaScript objects store data as key-value pairs. Swapping keys and values creates a new object where the original values become keys and the original keys become values.
- Create a new object to store the swapped key-value pairs.
- Iterate through the original object's properties.
- Assign each value as a key and its corresponding key as the value.
Note: Object keys must be unique. If multiple properties have the same value, later values can overwrite earlier ones when the object is swapped.
Approach 1: Using a for...in Loop
In this approach, a for...in loop iterates through each property of the object. A new object is created by assigning the original value as the key and the original key as its value.
const obj = {
Prop_1: "Val_1",
Prop_2: "Val_2",
Prop_3: "Val_3"
};
function swapKeysAndValues(object) {
const result = {};
for (const key in object) {
if (Object.hasOwn(object, key)) {
result[object[key]] = key;
}
}
return result;
}
const swappedObject = swapKeysAndValues(obj);
console.log(swappedObject);
Output
{ Val_1: 'Prop_1', Val_2: 'Prop_2', Val_3: 'Prop_3' }
Approach 2: Using Object.keys() and forEach()
In this approach, Object.keys() returns an array containing the object's keys. The forEach() method then iterates through these keys and creates the swapped object.
let obj = {
"Prop_1": "Val_1",
"Prop_2": "Val_2",
"Prop_3": "Val_3"
};
function swapValues(o) {
const res = {};
Object.keys(o).forEach(key => {
res[o[key]] = key;
});
return res;
}
function GFG_Fun() {
console.log(JSON.stringify(swapValues(obj)));
}
GFG_Fun();
Output
{"Val_1":"Prop_1","Val_2":"Prop_2","Val_3":"Prop_3"}
Approach 3: Using Object.entries() and reduce()
In this approach, Object.entries() converts the object's key-value pairs into an array. The reduce() method then creates a new object with the keys and values swapped.
const obj = {
Prop_1: "Val_1",
Prop_2: "Val_2",
Prop_3: "Val_3"
};
const swappedObject = Object.entries(obj).reduce(
(result, [key, value]) => {
result[value] = key;
return result;
},
{}
);
console.log(swappedObject);
Output
{ Val_1: 'Prop_1', Val_2: 'Prop_2', Val_3: 'Prop_3' }
Note: Although this operation is often described as swapping keys and values of a JSON object, JSON itself is a data format. In JavaScript, the swapping operation is performed on a parsed JavaScript object.