'How do I set multiple values in a Javascript Map at once?

I have a simple chain of logic here, where bigCities is a Javascript Map. In this example, d represents each object in an array of data read in from a csv file. For every object's city property, I'm assigning it's d.pop value (the population of the city).

bigCities.set(d.city, +d.pop)

What if I want to be able to set multiple values at once? Would the code look something like this:

bigCities.set(d.city, ["population": +d.pop, "latitude": +d.lat, "longtitude": +d.lng)

Is it possible to create a key value pair in a Javascript Map, where the value is an array of data? If so, how would I write the above example correctly?



Solution 1:[1]

To set multiple keys and values at a Map object you can pass an array of arrays

let m = new Map([["a", [1,2,3]], ["b", [4,5,6]]]);

console.log([...m], m.get("a"))

Solution 2:[2]

I think what you're looking for is an object that has three properties on it. You can make the city the key and an object like that be the value in the Map by setting it like this:

bigCities.set(d.city, {"population": +d.pop, "latitude": +d.lat, "longitude": +d.lng});

Then, to read it back again, you'd do this:

let info = bigCities.get(d.city);
console.log(info.population);
console.log(info.latitude);
console.log(info.longitude);

Hopefully, you recognize the syntax:

{"population": +d.pop, "latitude": +d.lat, "longitude": +d.lng}

as a Javascript literal object declaration. This creates a Javascript object with three property/value pairs where you reference the property by name.

Solution 3:[3]

const map = new Map();

    map.set("a", "alpha").set("b", "beta").set("c", "charlie");

    console.info(map); // Map(3) {'a' => 'alpha', 'b' => 'beta', 'c' => 'charlie'}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guest271314
Solution 2
Solution 3 Doni Darmawan