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


Here, we will learn to swap the key and value of the JSON element using JavaScript. In JavaScript, an object stores the key-value pairs. So, we can swap the key and value as we swap two normal variables.

In this tutorial, we will learn different approaches to swapping all the key values of JSON elements using JavaScript.

Use the for loop

We can iterate through the keys of the JSON object using for loop. After that, we can access the value from the object using the key. So, we can swap every key and value in the object.

Also, we need to create a new empty object and store the object's key and values after swapping.

Syntax

Users can follow the syntax below to use the for-loop to swap keys and values in the JSON element.

for (let key in object) {
   let value = object[key];
   new_obj[value] = key;
} 

In the above syntax, we have used the key to access its value from the object, and for new_obj, we used value as the key and key as a value.

Example 1

In the example below, we have created the object containing the unique key-value pairs. Also, we created the empty new_obj object to store keys and values after swapping. After that, we used the for loop to iterate through the keys of the object. Into the for loop, we access the value of the particular key from the JSON element.

We add the key and values from the object to the new_obj object, but we use values as a key and key as a value to swap. In the output, users can observe the key-value pairs of the new_obj, which are swapped.

<html>
<body>
   <h2>Using the <i> for loop </i> to swap keys and values of JSON elements</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let object = {
         "key1": true,
         "key2": 10,
         "key3": "hello",
         "key4": 40
      }
      let new_obj = {};
      for (let key in object) {
         let value = object[key];
         new_obj[value] = key;
      }
      output.innerHTML += "The old object is " + JSON.stringify(object) + "<br/>";
      output.innerHTML += "The new object after swapping the key and values is " + JSON.stringify(new_obj) + "<br/>";
   </script>
</body>
</html>

Use the Object.keys() and forEach() method

We can use the Object.keys() method to get the object's keys in the array format. After that, we can use the forEach() method to iterate through the array of keys.

While iterating through all the keys, we can access the value of the particular key and use it as a key for the new object.

Syntax

Users can follow the syntax below to use the Object.keys() and forEach() method to swap all keys and values of the JSON object.

Object.keys(student_obj).forEach((objectKey) => {
   swapped_obj[ student_obj[objectKey] ] = objectKey;
})

In the above syntax, we get value from the object using the ‘student_obj[objectKey]’, which works as a key of the swapped_obj object.

Example 2

In this example, we have created the student_obj object, which contains the various properties of the student and its value. After that, we used the Object.entries() and forEach() method to swap all keys and values of the object and store it to the swapped_obj object.

<html>
<body>
   <h2>Using the <i> Object.keys() and forEach() methods </i> to swap keys and values of JSON elements.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      let student_obj = {
         "name": "Shubham",
         "age": 22,
         "hobby": "Writing",
         "Above18": true,
         "id": "waewr34fg7y657"
      }
      let swapped_obj = {};
      Object.keys(student_obj).forEach((objectKey) => {
         let keyvalue = student_obj[objectKey];
         swapped_obj[keyvalue] = objectKey;
      })
      output.innerHTML += "The old object is " + JSON.stringify(student_obj) + "<br/>";
      output.innerHTML += "The new object after swapping the key and values is " + JSON.stringify(swapped_obj) + "<br/>";
   </script>
</body>
</html>

Use the Object.entries() and map() method

We can use the Object.entries() method to get all keys and values of the object in the array format. We can use the map() method to map new key-value pairs after swapping the old key-value pair.

We can use the array destructuring property to swap every key and value pair.

Syntax

Users can follow the syntax below to use the Object.entries() and map() method to swap the key and values of the JSON element.

const result = Object.entries(table).map(
   ([prop, propValue]) => { return [propValue, prop]; }
);
let newObject = Object.fromEntries(result);

We have reversed the order of every key and value pair in the above syntax. So, the key becomes a value, and value becomes the key. Also, we used the Object.fromEntries() method to create an object from the entries of keys and values.

Example 3

In this example, We have defined the table object containing the properties of the table. When a user clicks the button, it invokes the swapKeyValues() function.

In the swapKeyValues() function, we swap every key and value pair of objects and store them in the finalObject array. Afterwards, we used the Object.fromEntries() method to convert the finalObject array into the JSON object and stored it in the newObject variable

<html>
<body>
   <h2>Using the <i> Object.entries() and map() methods </i> to swap keys and values of JSON elements.</h2>
   <div id = "output"></div>
   <button onclick = "swapKeyValues()"> Swap Object key values</button>
   <script>
      let output = document.getElementById('output');
      let table = {
         "id": "1234",
         "color": "blue",
         "size": "6 feet",
         "legs": "6",
         "chairs": "8",
      }
      function swapKeyValues() {
         output.innerHTML += "The initial object is " + JSON.stringify(table) + "<br/>";
         let objectEntries = Object.entries(table);
         const finalObject = objectEntries.map(
            ([prop, propValue]) => { return [propValue, prop]; }
         );
         let newObject = Object.fromEntries(finalObject);
         output.innerHTML += "The new object after swapping the key and values is " + JSON.stringify(newObject) + "<br/>";
         return;
      }
   </script>
</body>
</html>

We learned three approaches to swap the key and values of JSON elements. Also, we can use the array.reduce() method with Object.entries() method to swap the key and values of the object.

Updated on: 16-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements