How to Convert Between Data Structures in JavaScript

Objects, arrays, sets, maps, and more

Cristian Salcescu
Frontend Essentials

--

Photo by the author

JavaScript has several built-in data structures and in this article, we will look at how to convert between the most used of them: objects, arrays, sets, and maps.

Objects are collections of key-value pairs with a hidden property to their prototype.

Arrays are indexed collections of values.

Sets are collections of unique values.

Maps are collections of key-value pairs.

Objects and Maps

As we can see the definition of both objects and maps is pretty similar, they are both collections of key-value pairs so it is easier to convert between them.

Objects to Maps

Consider the following object storing translations.

const obj = {
"Hi": "Hola",
"Bye": "Adios"
}

We can convert it to a map using the Object.entries helper and the Map constructor.

The Object.entries helper returns an array of [key, value] pairs for the given object. It returns only the owned properties, not the ones inherited from the prototype.

console.log(Object.entries(obj))
//[
//["Hi", "Hola"],
//["Bye"…

--

--