0

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?

2
  • 6
    Why not create an object that maps these letters to these numbers, e.g. const obj = {'b': 1, 'd': 3, 'f': 5} then when you want to print the corresponding number do: obj['b'] or obj.b Commented Aug 17, 2019 at 0:04
  • 1
    That's actually exactly what I ended up doing. Post as answer and will mark. Thanks! Commented Aug 17, 2019 at 0:42

1 Answer 1

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.

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

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.