how to create a map in javascript with array of values dynamically

28,207

Solution 1

I think this is what you are asking. addValueToList will create array/list dynamically if the key is not present in the map.

//initially create the map without any key
var map = {};

function addValueToList(key, value) {
    //if the list is already created for the "key", then uses it
    //else creates new list for the "key" to store multiple values in it.
    map[key] = map[key] || [];
    map[key].push(value);
}

Solution 2

You can use the arguments list to populate your object with key corresponding to the strings passed in as arguments. Then you can write another function to populate this map with data.

var createMap = function() {
    var map = {};
    Array.prototype.slice.call(arguments).forEach(function ( arg ) {
        map[arg] = null;
    });
    return map;
}

So createMap('para1', para2', para3') will return an object with 3 keys: para1, para2, para3. All having null as value. You can obviously replace null with a reference to the data you want the key to have, if you want to do it all in one function.

Share:
28,207
Zack
Author by

Zack

Updated on July 17, 2022

Comments

  • Zack
    Zack almost 2 years

    I have this requirement. Depending on the number of arguments passed in the function, I need to create that many entries in my map. Say I have a function myfunc1(a,b,c) , I need to have a map with the keys as "a","b" and "c" and I can have more than one values for each of the keys. But the problem is that I do not know beforehand, how many values will come for those keys. As and when the values come, I need to add them to the list of values corresponding to the matching key in the map. How do I do this in javascript? I have found static answers like below. But I want to do this dynamically. Can we use the push method ?

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