How to exchange keys and values of JSON elements using JavaScript?
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; }
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>
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; })
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>
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);
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
