1

Is there a way to call a variable based on the value of another variable, which is not always the same?

Example:

var color = 'black';
var [color] = 'whatever'; // the variable name here would be 'black'

Reason for usage: In the reducer of Redux I receive an action that holds a particular value

export default (state = INITIAL_STATE, action) => {
const { size, color, object } = action;
switch (action.type) {
    case (DO_SOMETHING): {
    // instead of name 'output' below, I want to have a value of 'color' 
        let output = object;
        if (size) { 
            output = callExternalFunction(output, size);
        }
        return { ...state, [color]: output };
    }

My goal: If it is possible to do, I will be able to turn the return into this:

return { ...state, [color] };

2 Answers 2

0

Why not just use an object to hold your variables names? For instance :

var color = 'black',
    variables = {};

variables[color] = 'whatever'; // { black : 'whatever' }

return { ...state, variables['black'] } // { ...state, 'whatever' }

Does that fit your needs? Maybe I misunderstood the question

5
  • The whole and only purpose of this struggle is merely to condense the size of the code by a few characters. And your solution does not achieve that.
    – Eduard
    Sep 21, 2017 at 9:32
  • Oh, so your code works, but you just wanted to make it shorter? I didn't get your point then. Sep 21, 2017 at 9:44
  • I was not specific enough in the post :)
    – Eduard
    Sep 21, 2017 at 9:57
  • In the return statement how do you know variables['black'] the value name is "black".You have hardcoded it.
    – pritesh
    Sep 21, 2017 at 10:04
  • 1
    It should return variables[color]
    – pritesh
    Sep 21, 2017 at 10:08
0

You can use window object for that. Try this:

var color = 'black';
window[color] = 'whatever';
alert(black);

Edit:

As @Tavish Aggarwal mentioned this will make the variable global, if you really don't want that you could use eval() instead.

But eval is evil, as the saying goes, so I don't recommend it.

6
  • Seems to work, but is it a reasonable and practical way of doing for the sake of mere condensation of the code?
    – Eduard
    Sep 21, 2017 at 9:37
  • 2
    @Eduard attaching variable to window is not a good practice. As it makes it a global variable. Sep 21, 2017 at 9:40
  • @TavishAggarwal I see, probably should just leave the code in a way it is now. Thanks!
    – Eduard
    Sep 21, 2017 at 9:42
  • I thought about using window, but I wanted to avoid using a global variable. That's why I suggested using a local object instead of window. Sep 21, 2017 at 9:43
  • Yes, but code suggested by you is not what @Eduard want. Sep 21, 2017 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.