Search code examples
javascriptarraysecmascript-6getter-setter

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

  • 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"))