0

I have an object called assignments which contains arrays as such;

assignments = {
    'version_1': [1,2,3,4,5],
    'version_2': [6,7,8,9,0],
    'version_3': [3,4,5,6,7]
}

if I want to get the values of a particular version I can simply say something like console.log(assignments.version_2);

But what if I have an integer set in a variable? How would I reference the values dynamically. e.g.

var version_id = 2;
console.log(assignments.version_[version_id]);
JJJ
  • 32,902
  • 20
  • 89
  • 102
Typhoon101
  • 2,063
  • 8
  • 32
  • 49
  • 3
    Possible duplicate of [How to access object using dynamic key?](https://stackoverflow.com/questions/6921803/how-to-access-object-using-dynamic-key) – JJJ Oct 30 '17 at 09:08

3 Answers3

2

You can use this :

var version_id = 2;
console.log(assignments["version_" + version_id]);

Or, if you know you only have to support browsers that have es6, you can do :

assignments[`version_${version_id}`] 

Es6 template strings make things nicer

GGO
  • 2,678
  • 4
  • 20
  • 42
0

Try following

var assignments = {
  'version_1': [1, 2, 3, 4, 5],
  'version_2': [6, 7, 8, 9, 0],
  'version_3': [3, 4, 5, 6, 7]
};

var version_id = 2;

console.log(assignments["version_" + version_id]);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

assignments = {
    'version_1': [1,2,3,4,5],
    'version_2': [6,7,8,9,0],
    'version_3': [3,4,5,6,7]
}
console.log(assignments['version_2'])
vicky patel
  • 699
  • 2
  • 8
  • 14