How To Swap The Keys And Values In An Object In JavaScript

Swap the Keys and Values in an Object in JavaScript

In this article, you’ll learn how to swap the keys and values in an object in JavaScript by iterating over the original object or using the Object.fromEntries() and .reverse() functions. Let’s go into detail now.

Swap the keys and values in an object in JavaScript

For anyone who doesn’t remember, an Object is a collection of unique key-value pairs.

Generally, when dealing with any problem relating to its keys and values, you use the Object class’ static functions Object.keys() and Object.values() or Object.entries() (though this you would generally only use for iterating).

  • Object.keys(object): Returns an array containing all of the object’s keys.
  • Object.values(object): Returns an array containing all of the object’s values.
  • Object.entries(object): Returns an array of key-value pair arrays from the object.

Looping over the original object

Simply iterate over the original Object, then add the value-key (i.e., key-value but swapped) pairs to a new Object. As such:

Code:

const obj = {
	"key1": 3,
	"key2": 3,
	"key3": 3,
	"key4": "LearnShareIT"
}

function switchKeyValue(obj) {
	const newObj = {}

	for (const [key, value] of Object.entries(obj)) {
		newObj[value] = key;
	}

	return newObj;
}

console.log(switchKeyValue(obj));

Output:

{ 3: "key3", LearnShareIT: "key4" }

You may have noticed an issue with the fact that the new Object only has 2 values as compared to the original’s 4. The issue is that the value "3" appears in keys 1 through 3; and that when using those repeating values as a key in line 10, the code registers it as replacing the value of key "3" instead of creating a new value-key pair.
You cannot have duplicate keys in an Object; that is just a stated fact. However, you can have an array as a value in an Object; so to deal with the problem, you can do something like this:

Code:

const obj = {
	"key3": 3,
	"key1": "LearnShareIT",
	"key2": 3,
	"key4": 3,
}

function switchKeyValue(obj) {
	const newObj = {}
	for (const [key, value] of Object.entries(obj)) {

		// Check if there's a duplicate key (i.e. value)
		if (value in newObj && typeof newObj[value] !== "object") newObj[value] = [key];

		// Check if the current key (i.e. value) is an array or not
		if (typeof newObj[value] === "object") newObj[value].push(key);
		else newObj[value] = key;
	}
	return newObj;
}

console.log(switchKeyValue(obj));

Output:

{ 3: ["key1", "key2", "key3"], LearnShareIT: "key4" }

Using Object.fromEntries() and Array.prototype.reverse()

The Object.fromEntries() function takes an array of entries (i.e. an array containing a pair of key and value) and converts it into an Object.

The Array class’ .reverse() function takes an array and reverses its order.

With these two functions, the solution is simple: Take an Object and create an array of entries with the Object.entries() function then reverse the order of those entries using the .reverse() function, then create a new Object using those entries. As such:

Code:

const obj = {
	"key1": "LearnShareIT",
	"key2": 3,
	"key3": 3
}

// Spaced for easier viewing
console.log(
	Object.fromEntries(
		Object.entries(obj).map(v => v.reverse())
	)
);

Output:

{ 3: "key3", LearnShareIT: "key1" }

While this method is much simpler and faster performance-wise, it will not be able to contain every value of a duplicate key.

Summary

To swap the keys and values in an object using JavaScript, you can iterate over the object then add the value-key pairs onto a new object; or create a list of reversed entries and create a new object with the Object.fromEntries() function. Although generally if you don’t care about duplicate values becoming the same key, it’s preferred that you use the Object.fromEntries() method and if you do care, use the former method.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *