Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: access an object property whose name starts with a number

I'm creating a Javascript / jQuery application.

I need to process a JSON response that represents a HashMap, like this:

  {
    "accounts": {
      "MediaFire": {
       "provider": "MediaFire",
       "usedStorage": "779680",
       "totalStorage": "53687091200"
      },
      "4Sync": {
       "provider": "4Sync",
       "usedStorage": "620692",
       "totalStorage": "16106127360"
      }
    }
  }

I use a pasing function (which I can't control), which returns the parsed JSON response in an object result.

When I try to access the 4Sync like this:

var usedStorage = result.accounts.4Sync.usedStorage; //doesn't work

it doesn't work, I think it's because of the 4 at the beginning... The same operation with the other object works fine:

var usedStorage = result.accounts.MediaFire.usedStorage; //works

I know the result object contains the object 4Sync, but I can't access it. Here is a screenshot of Chrome's console:

screenshot of Chrome's console

Is there any workaround to solve this?

like image 491
MikO Avatar asked Jan 14 '23 15:01

MikO


1 Answers

Use square brackets:

var usedStorage = result.accounts["4Sync"].usedStorage;

Property identifers can begin with a number, but member expressions with the . character will only allow valid variable identifiers (since anything else is ambiguous). To get around this, you can use the square bracket syntax, which is equivalent but allows the use of any string.

If you're interested, here is the grammar:

MemberExpression :
    PrimaryExpression
    FunctionExpression
    MemberExpression [ Expression ]
    MemberExpression . IdentifierName

Notice how square brackets can contain any expression, but the . can only be followed by an IdentifierName (basically, any valid identifier, plus reserved words in ES5).

like image 130
James Allardice Avatar answered Jan 31 '23 06:01

James Allardice