Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to swap the key and value of JSON element using JavaScript?
Here, we will learn to swap the key and value of JSON elements using JavaScript. In JavaScript, an object stores key-value pairs, and we can swap the key and value just like swapping two normal variables.
In this tutorial, we will learn different approaches to swapping all the key-values of JSON elements using JavaScript.
Using the for...in Loop
We can iterate through the keys of the JSON object using a for...in loop. After that, we can access the value from the object using the key and swap every key-value pair in the object.
We need to create a new empty object and store the object's key and values after swapping.
Syntax
for (let key in object) {
let value = object[key];
new_obj[value] = key;
}
In the above syntax, we use the key to access its value from the object, and for new_obj, we use value as the key and key as the value.
Example
In the example below, we have created an object containing unique key-value pairs. We also created an empty new_obj object to store keys and values after swapping. We use the for loop to iterate through the keys of the object and swap them.
<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>
The old object is {"key1":true,"key2":10,"key3":"hello","key4":40}
The new object after swapping the key and values is {"10":"key2","40":"key4","true":"key1","hello":"key3"}
Using Object.keys() and forEach() Method
We can use the Object.keys() method to get the object's keys in 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
Object.keys(object).forEach((objectKey) => {
swapped_obj[object[objectKey]] = objectKey;
})
In the above syntax, we get the value from the object using 'object[objectKey]', which works as a key for the swapped_obj object.
Example
In this example, we have created the student_obj object, which contains various properties of the student and their values. We use the Object.keys() and forEach() method to swap all keys and values of the 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>
The old object is {"name":"Shubham","age":22,"hobby":"Writing","Above18":true,"id":"waewr34fg7y657"}
The new object after swapping the key and values is {"Shubham":"name","22":"age","Writing":"hobby","true":"Above18","waewr34fg7y657":"id"}
Using Object.entries() and map() Method
We can use the Object.entries() method to get all keys and values of the object in array format. We can use the map() method to map new key-value pairs after swapping the old key-value pairs.
We can use array destructuring to swap every key and value pair efficiently.
Syntax
const result = Object.entries(object).map(
([prop, propValue]) => { return [propValue, prop]; }
);
let newObject = Object.fromEntries(result);
We reverse the order of every key and value pair in the above syntax. The key becomes a value, and the value becomes the key. We use the Object.fromEntries() method to create an object from the entries of keys and values.
Example
In this example, we have defined the table object containing properties of the table. When a user clicks the button, it invokes the swapKeyValues() function to swap every key and value pair.
<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>
The initial object is {"id":"1234","color":"blue","size":"6 feet","legs":"6","chairs":"8"}
The new object after swapping the key and values is {"1234":"id","blue":"color","6 feet":"size","6":"legs","8":"chairs"}
Comparison
| Method | Readability | Performance | Modern JS |
|---|---|---|---|
| for...in loop | Good | Fast | Traditional |
| Object.keys() + forEach() | Very Good | Medium | Modern |
| Object.entries() + map() | Excellent | Medium | Most Modern |
Important Considerations
When swapping keys and values, ensure that all values are strings, numbers, or other primitive types that can be used as object keys. If values are objects or arrays, they will be converted to strings when used as keys.
Conclusion
We learned three effective approaches to swap keys and values of JSON elements in JavaScript. The Object.entries() with map() method is the most modern and readable approach, while the for...in loop offers the best performance for large objects.
