javascriptsyntaxsyntax-error

How can I construct an object with keys that contain hyphens?


I have below working fine:

var varName= {
    variable_one: 'short_name',
    variable_two: 'long_name',
    variable_three: 'long_name',
    variable_four: 'short_name',
    variable_five: 'long_name',
    variable_six: 'short_name'
};

but if i change into:

var varName= {
    variable-one: 'short_name',
    variable-two: 'long_name',
    variable-three: 'long_name',
    variable-four: 'short_name',
    variable-five: 'long_name',
    variable-six: 'short_name'
};

it show me error:

Unexpected token -

then the question is: how do it escape the '-' because i need the name with '-' instead of '_'

i tried to put ''' or '"' but didn't work T_T

Thanks


Solution

  • This should work for you

    let varName= {
        'variable-one': 'short_name',
        'variable-two': 'long_name',
        'variable-three': 'long_name',
        'variable-four': 'short_name',
        'variable-five': 'long_name',
        'variable-six': 'short_name'
    };
    

    JavaScript takes the - as a literal minus sign.