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] };
Eduard
  • 8,437
  • 10
  • 42
  • 64

2 Answers2

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

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
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.

Fuross
  • 488
  • 6
  • 12