0

just started to dabble with Javascript so I'm sorry if this is a basic question. I have an array of keys:

keys = ['fruits','vegetables','fats','meats']

I want to dynamically create a Map for each of these elements in the array (the length of this array may change). I'm trying to do something like this:

for (var i=0; i<keys.length; i++) {
    map_name = keys[i];
    var map_name = new Map();
    map_name.set('foo','bar');
}
console.log(fruits)

Output: fruits is not defined

I've tried searching for some kind of syntax to be able to dynamically create this while also being able to access the Maps that are created globally, but I can't seem to find a solution.

Thank you!

3
  • please add an example of the wanted map as well. you have only keys, but no values. Commented May 6, 2017 at 8:21
  • Hi Nina, I'll get the values for each key from a json file Commented May 6, 2017 at 8:25
  • ok, but can you add an example of what you have and what you want? Commented May 6, 2017 at 8:26

2 Answers 2

0

Trying to create variable names dynamically is a bad idea. Use a map instead:

var keys = ['fruits','vegetables','fats','meats'];

var things = new Map();
for (var i=0; i<keys.length; i++) {
    var map_name = keys[i];
    var map_value = new Map();
    map_value.set('foo', 'bar');
    things.set(map_name, map_value);
}

console.log(things.get('fruits').get('foo'));

Sign up to request clarification or add additional context in comments.

Comments

-1

try this

keys = ['fruits','vegetables','fats','meats']

for (var i=0; i<keys.length; i++) {
    map_name = keys[i];
    window[map_name] = new Map();
    window[map_name].set('foo','bar');
}

console.log(fruits)

By setting your keys as properties of window object you can access it by just using variable name directly, like 'fruits'.

But in practice it is not recommended to add properties to window object. You should use your own object for that.

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.