In this article, we will swap the key and value of JSON elements using JavaScript. Given a JSON object and the task is to swap the JSON object key with values and vice-versa with the help of JavaScript.
Below are the following approaches:
Approach 1: Using for loop
- Create a new empty object.
- Visit every key of an object by for loop and add the elements from the old object to the new object in reverse form(by swapping the key and values).
Example: This example implements the above approach.
Javascript
let obj = {
"Prop_1" : "Val_1" ,
"Prop_2" : "Val_2" ,
"Prop_3" : "Val_3"
};
function swapValues(j) {
let res = {};
for (let key in j) {
res[j[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"}
- Create a new empty object.
- For each key of the object, add the elements from the old object to the new object in reverse form (by swapping the key and values).
Example: This example implements the above approach.
Javascript
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"}
In this method, we will use Object.entries() and map() Methods to get all the key values of the object in the array format.
Example:
Javascript
let obj = {
"Prop_1" : "Val_1" ,
"Prop_2" : "Val_2" ,
"Prop_3" : "Val_3"
};
const swappedObject =
Object.entries(obj).reduce((acc, [key, value]) => {
acc[value] = key;
return acc;
}, {});
console.log(swappedObject);
|
Output{ Val_1: 'Prop_1', Val_2: 'Prop_2', Val_3: 'Prop_3' }