9

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"];
0

2 Answers 2

19

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

We now have a shortcut operator that does the null/else check: map[key] ??= [] which has 84% global browser support at the time of this comment.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.