To convert an object to a Map
in JavaScript, you can use the Object.entries()
method to get an array of key-value pairs from the object, and then create a new Map
object using the Map
constructor and the obtained array.
Here's an example of how you can convert an object to a Map
using Object.entries()
:
const user = {
name: 'John Doe',
age: 20,
job: 'Engineer'
}
const kvPairs = Object.entries(user)
const map = new Map(kvPairs)
console.log(map)
// Map(3) { 'name' => 'John Doe', 'age' => 20, 'job' => 'Engineer' }
In this example, Object.entries(user)
returns an array of key-value pairs from the user
object, which is then used to create a new Map
object using the Map
constructor.
Alternatively, you can use the Array.forEach()
method to iterate over the object keys and add each key-value pair to the Map
using the Map.set()
method:
const user = {
name: 'John Doe',
age: 20,
job: 'Engineer'
}
const map = new Map()
Object.keys(user).forEach(key => {
map.set(key, user[key])
})
console.log(map)
// Map(3) { 'name' => 'John Doe', 'age' => 20, 'job' => 'Engineer' }
In this example, Object.keys(user)
returns an array of keys from the user
object. We then iterate over these keys using forEach()
and use the Map.set()
method to add each key-value pair to the map
object.
If you want to convert the Map
object back to an object, you can use the Object.fromEntries()
method:
const map = new Map([
['name', 'John Doe'],
['age', 20],
['job', 'Engineer']
])
const user = Object.fromEntries(map)
console.log(user)
// { name: 'John Doe', age: 20, job: 'Engineer' }
The Object.fromEntries()
method takes an iterable of key-value pairs, such as an array, and returns a new object with the key-value pairs.
To learn more about the Map
object and how to create collections of key-value pairs in JavaScript, you can refer to this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.