简体   繁体   中英

How to create map with key and a list of values in JavaScript

In Java we can create

private map<String, List<String>> map = HashMap<String, ArrayList<String>();

How to create a map with keys and lists of values in JavaScript?

I want to put key as country name and list of values are country states. How to do in JavaScript?

map = {"country1": ["state1", "state2"], "country2": ["state1", "state2"]}

OR dynamically

var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];

Here a java and javascript coder.

 //Variable map, contains a instance of Map with a constructor of String and Array of String. let map = new Map([[String.prototype, [String.prototype]]]); //Put values in map. map.set('Country1', ['State1', 'State2']); map.set('Country2', ['State1', 'State2', 'State3']); map.set('CountryN', ['State1', 'State2', 'State3', 'StateN']); //Iterate map and print the content of this. map.forEach((value, key) => { console.log(`Country: ${key} States:[${value}]`); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM