-2

I am currently extracting data from a JSON array that looks like the following

    "title": Title,
    "chapters": {
        "13c": {
            "words": 123,
            "spaces": 321
        },
        "15d": {
            "words": 123,
            "spaces": 321
        },
        "38h": {
            "words": 123,
            "spaces": 321
        }
    }

The thing is when I try to select 13c (if it exists) with the following

if(book.chapters.13c){
     console.log(book.chapters.13c);
}

I get the following error:

Uncaught SyntaxError: Unexpected token ILLEGAL

2 Answers2

2

For every situation you find yourself unable to use the . syntax, use the [] syntax instead:

console.log(book.chapters['13c']);

Note that the [] syntax and . syntax are equivalent but the [] syntax is more flexible since it has no restriction on the attribute key. For example, if your property key contains whitespace:

book.chapters['hello world'];

if your property key needs to be constructed from variables:

book.chapters[somevar + '-' + someothervar];

etc.

In javascript, foo.bar is just shorthand for foo['bar'].

slebetman
  • 109,858
  • 19
  • 140
  • 171
1

You can do:

if(book.chapters["13c"]) ...

That is functionally equivalent to what you want. Normally you shouldn't use Numbers at the start of an identifier but it is valid. Since it is parsed as a string it is the same.

It is equivalent to creating an object like so:

{
  "0":true,
  "1":"testing",
  "2":"yup",
  "length": 3
}
MiltoxBeyond
  • 2,683
  • 1
  • 13
  • 12