Table of Contents
Many still have a problem while they convert an array of objects to a map in JavaScript. The question here is: Is there any correct yet straightforward approach to get such a task done less strugglingly? Let’s find out!
How To Convert An Array Of Objects To A Map?
Little did you know, there are actually more than one way to create a map using an array. The list includes:
- Utilizing map() method.
- Utilizing map.set() method.
- Passing An Array Of Key-Value Pairs
Wait for no more but dig in to see in details!
Convert Array Of Objects To A Map Using Map() Method
Similar to how traditional arrays work, map() function may also be of great use to loop through an array of objects, change the contents of each individual item, and then return a new array. Based on the results of the callback function, this update is made.
Here’s an illustration:
const myUsers = [
{ name: 'shark', likes: 'ocean' },
{ name: 'turtle', likes: 'pond' },
{ name: 'otter', likes: 'fish biscuits' }
]
const usersByLikes = myUsers.map(item => {
const container = {};
container[item.name] = item.likes;
container.age = item.name.length * 10;
return container;
})
console.log(usersByLikes);
Ouput:
Output
[
{shark: "ocean", age: 50},
{turtle: "pond", age: 60},
{otter: "fish biscuits", age: 50}
]
The dot notation and bracket was used to modify each object in the array in this case. Before data is stored or processed on a front-end application, this use case can be used to process or compress the data that has been received.
Convert Array Of Objects To A Map Using Map.set() Method
Otherwise, you can also employ the map.set() feature to complete the converting mission. With this method, we will be able to generate a Map by adopting the new keyword and placing elements inside it.
Let’s look at the following example:
let map = new Map();
map.set("1","first element");
map.set(1, "second element");
map.set(true, "hello world");
Convert Array Of Objects To A Map By Passing An Array Of Key-Value Pairs
We may also supply an array of key-value pairs to initialize a Map rather than adding entries utilizing map.set().
For example:
let map = new Map([
["1", "first element"],
[1, "second element"],
[true, "hello world"]
]);
As such, it will make more sense to set up a Map with an array of key-value pairs rather than with map.set() when we need to add a lot of components to it.
The Bottom Line
Above is all you may yearn to acquire regarding how to convert an array of objects to a map. Hopefully, this article will be a full-package to your map-related roughhouse in Java or JavaScript (such as how to instantiate map or so). See you then!
Leave a comment