Home > Web Front-end > JS Tutorial > How to exchange keys and values ​​of JSON elements using JavaScript?

How to exchange keys and values ​​of JSON elements using JavaScript?

WBOY
Release: 2023-08-23 22:41:05
forward
756 people have browsed it

如何使用 JavaScript 交换 JSON 元素的键和值?

Here we will learn to exchange the keys and values ​​of JSON elements using JavaScript. In JavaScript, objects store key-value pairs. Therefore, we can swap the key and value just like we swap two normal variables.

In this tutorial, we will learn different ways to exchange all key values ​​of a JSON element using JavaScript.

Use for loop

We can use a for loop to iterate over the keys of a JSON object. After that we can access the value from the object using the key. Therefore, we can exchange every key and value in the object.

Additionally, we need to create a new empty object and store the keys and values ​​of that object after swapping.

grammar

Users can use the for loop to exchange keys and values ​​in JSON elements according to the following syntax.

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

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

Example 1

In the following example, we create an object containing unique key-value pairs. Additionally, we create an empty new_obj object to store the swapped keys and values. After that, we use a for loop to iterate over the keys of the object. In the for loop, we access the value of a specific key from the JSON element.

We add the keys and values ​​from the object to the new_obj object, but we use the value as the key and the key as the value to be swapped. In the output, the user can observe that the key-value pairs of new_obj are exchanged.

<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>
Copy after login

Use Object.keys() and forEach() methods

We can use the Object.keys() method to get the keys of the object in array format. Afterwards, we can use the forEach() method to iterate over the keys array.

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

grammar

Users can use the Object.keys() and forEach() methods according to the following syntax to exchange all keys and values ​​of the JSON object.

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

In the above syntax, we use "student_obj[objectKey]" to get the value from the object, which serves as the key of the swapped_obj object.

Example 2

In this example, we created the student_obj object, which contains various attributes of student and their values. After that, we swap all the keys and values ​​of the object using Object.entries() and forEach() methods and store it into 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>
Copy after login

Use Object.entries() and map() methods

We can use the Object.entries() method to get all the keys and values ​​of the object in array format. After exchanging the old key-value pairs, we can use the map() method to map the new key-value pairs.

We can use array destructuring properties to exchange each key and value pair.

grammar

Users can use the Object.entries() and map() methods according to the following syntax to exchange the keys and values ​​of JSON elements.

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

We reversed the order of each key and value pair in the above syntax. So keys become values ​​and values ​​become keys. Additionally, we create an object from the entries of keys and values ​​using the Object.fromEntries() method.

Example 3

In this example, we define a table object that contains table properties. When the user clicks the button, it calls the swapKeyValues() function.

In the swapKeyValues() function, we swap each key and value pair of the object and store them in the FinalObject array. After that, we use the Object.fromEntries() method to convert the finalObject array into a JSON object and store 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>
Copy after login

We learned three ways to exchange the keys and values ​​of JSON elements. Additionally, we can use the array.reduce() method and Object.entries() method to exchange the keys and values ​​of objects.

The above is the detailed content of How to exchange keys and values ​​of JSON elements using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template