I am trying to make my code look a little prettier, which is a function that has maybe 16 arguments and does a lot of repeated code with these arguments.
Here's some sample code to demonstrate my problem:
function foo(varList, a, b, c, d, e, f, ...) {
varList.map(bar => {
console.log('Result: ' + bar);
}
}
const vars = ['b', 'd', 'f'];
foo(vars, 0, 1, 2, 3, 4, 5);
Results in
b, d, f
I am actually trying to access the data in those variable names instead, so it should print:
1, 3, 5
Is there a way to dynamically work with variables like this?
1 Answer 1
As @alfasin answered, just use the power of JavaScript Objects. An object consists of key-value pairs, where each key is a string and the corresponding value can be an arbitrary JavaScript object.
For your example code, you can simply write:
const vars = {'b': 1, 'd': 3, 'f': 5};
To access the value of a certain object key, either write vars.b or vars['b'] to access the value of b (which is 1) for example.
Comments
Explore related questions
See similar questions with these tags.
const obj = {'b': 1, 'd': 3, 'f': 5}then when you want to print the corresponding number do:obj['b']orobj.b