0

I tried Google this, but it's hard to explain what I am trying to do.

I am returned with a string var returnedString = model one.

Suppose I have a bunch of arrays called

var model_one   = ['a', 'b', 'c']
var model_two   = ['d', 'e', 'f']
var model_three = ['f', 'g', 'h']

This is what I have done

var selectedArrayName = returnedString.replace(" ", "_") //model_one

And this is what I want to do...

for (i in array with name selectedArrayName) {
    print selectedArrayName's array index. 
}  
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
dsomel21
  • 576
  • 2
  • 8
  • 27

2 Answers2

2

One way to approach this would be to create a dictionary of models, which can be accessed via bracket notation []:

var models = {
  model_one: ['a', 'b', 'c'],
  model_two: ['d', 'e', 'f'],
  model_three: ['f', 'g', 'h']
};
var modelName = 'model_one';

for(var index in models[modelName]) {
  var content = models[modelName][index];
  console.log(index, content);
}
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

If you are on the client side and not in a function, you could access it using

for (var i in window[selectedArrayName]) {
    // print selectedArrayName's array index. 
}

The better way, as suggested in the comment is to do something like

var models = {
    model_one: ['a', 'b', 'c'],
    model_two: ['d', 'e', 'f'],
    model_three: ['f', 'g', 'h']
};

for(var i in models[selectedArrayName]) {
    // print selectedArrayName's array index. 
}
jeff carey
  • 2,313
  • 3
  • 13
  • 17