Javascript: access to an object whose name begins with a number

I am creating a Javascript / jQuery application.

I need to process the JSON response that the HashMap represents, for example:

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

I use the pasing function (which I cannot control), which returns the parsed JSON response in the result object.

When I try to access 4Sync as follows:

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

it does not work, I think it is because of 4 at the beginning ... The same operation with another object works fine:

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

I know that the result object contains a 4Sync object, but I cannot access it. Here is a screenshot of the Chrome console:

screenshot of Chrome's console

Is there a way around the solution?

+4
source share
1 answer

Use square brackets:

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

Property identifiers may begin with a number, but member expressions with a symbol . only valid variable identifiers are allowed (since everything else is ambiguous). To get around this, you can use the square bracket syntax, which is equivalent but allows any string to be used.

If you're interested, here is the grammar :

MemberExpression:
Primary Expression
Expression Functions
MemberExpression [ Expression ]
MemberExpression . IDName

Please note that square brackets can contain any expression, but beyond . only an Identifier Name can follow (basically, any valid identifier plus reserved words in ES5).

+7
source

All Articles