Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"];
like image 747
Zack Avatar asked Oct 08 '15 15:10

Zack


People also ask

How do I map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

How do you turn an array of objects into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

Can we map an array?

To map an array to a non-array structure, you must use selectors in the expression. If the single element comes from an array (array parent) then you must manually add the array index to use. For example, $trigger. body.


2 Answers

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);
}
like image 51
rajuGT Avatar answered Nov 14 '22 23:11

rajuGT


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.

like image 34
Shilly Avatar answered Nov 14 '22 23:11

Shilly