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!

melpomene
  • 84,125
  • 8
  • 85
  • 148

2 Answers2

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'));
melpomene
  • 84,125
  • 8
  • 85
  • 148
-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.

HarshaXsoad
  • 776
  • 9
  • 30