julio julio - 4 months ago 19
Javascript Question

access javascript object with space in key

I have a javascript object that looks something like this:

myTextOptions: {
'cartoon': {
comic: 'Calvin & Hobbes',
published: '1993'
},
'character names': {
kid: 'Calvin',
tiger: 'Hobbes'
}
}


I can access the cartoon properties easily using
myTextOptions.cartoon.comic
or whatever. However, I haven't been able to get the syntax right for accessing
kid
. I've tried the following with no luck:

myTextOptions.character names.kid
myTextOptions."character names".kid
myTextOptions.character\ names.kid
myTextOptions.'character names'.kid
myTextOptions.["character names"].kid
myTextOptions.character%20names.kid

Answer

Use ECMAscripts "bracket notation":

myTextOptions[ 'character names' ].kid;

You can use that notation either way, reading & writting.

For more information read out here: