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]);
1

3 Answers 3

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

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

3 Comments

Perfect. Thanks.
@GGO - Added a missing closing brackets - Hope it is good with you
@Typhoon101 if you know you only have to support browsers that have es6, you cna do assignments[`version_${version_id}`] -- es6 template strings make things nicer
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]);

Comments

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'])

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.