Open In App

How to swap key and value of JSON element using JavaScript ?

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

Example: This example implements the above approach. 




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"}

Approach 2: Using Object.keys() and ForEach() Method

Example: This example implements the above approach. 




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 map() Method

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:




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' }


Article Tags :