How to Swap Keys and Values in Javascript

In this tutorial, you will learn how to swap keys and values in javascript. An object is nothing more than a collection of key-value pairs.  This key-value pair is known as the property of an object.

Unlike other primitive types, objects are of reference type. You will be surprised to know that primitive value null as well as an array is also an object. You can verify this with the help of the typeof operator.

If you are a newbie, then swapping keys and values in an object is not going to be easy. There are numerous ways to solve this problem, but I will show you the one which I think is simple and easy to understand. We are going to make use of Object.entries() method and forEach loop to accomplish our goal.

In the following example, we have an object stored in a global variable.  We will simply swap keys and values of this object and store the newly created object in a variable.  Finally, we will log that object in the console window.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We do not have any element in the HTML file because it is not required for this tutorial.
  • We have only included our javascript file script.js with a script tag at the bottom. The javascript code will run as soon as the page is loaded in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have an object stored in the myObject variable.
  • We have an empty object stored in the newObject variable.
  • We are using the Object.entries() method and passing myObject as a parameter. This method returns an array of the given object’s own enumerable string-keyed property [key, value] pairs.
  • We are using a forEach loop to iterate over the array. Each entry is an array and it contains only 2 items.  At the index of 0, we have a key and at the index of 1, we have value.
  • For each entry, we are storing the key in the key variable and the value in the value variable.
  • We are using the value variable as key and setting the key variable as its value in the newObject
  • .We are using the console.log() method to log newObject in the console window.
let myObject = {
    name: 'peter',
    age: '30',
    department: 'Sales'
};

let newObject = {};

Object.entries(myObject).forEach(entry =>{
    let key = entry[0];
    let value = entry[1];
    newObject[value] = key;
});

console.log(newObject);