jquery - Javascript: access an object property whose name starts with a number -
i'm creating javascript / jquery application.
i need process json response represents hashmap
, this:
{ "accounts": { "mediafire": { "provider": "mediafire", "usedstorage": "779680", "totalstorage": "53687091200" }, "4sync": { "provider": "4sync", "usedstorage": "620692", "totalstorage": "16106127360" } } }
i use pasing function (which can't control), returns parsed json response in object result
.
when try access 4sync
this:
var usedstorage = result.accounts.4sync.usedstorage; //doesn't work
it doesn't work, think it's because of 4 @ beginning... same operation other object works fine:
var usedstorage = result.accounts.mediafire.usedstorage; //works
i know result
object contains object 4sync
, can't access it. here screenshot of chrome's console:
is there workaround solve this?
use square brackets:
var usedstorage = result.accounts["4sync"].usedstorage;
property identifers can begin number, member expressions .
character allow valid variable identifiers (since else ambiguous). around this, can use square bracket syntax, equivalent allows use of string.
if you're interested, here the grammar:
memberexpression :
primaryexpression
functionexpression
memberexpression[
expression]
memberexpression.
identifiername
notice how square brackets can contain expression, .
can followed identifiername (basically, valid identifier, plus reserved words in es5).
Comments
Post a Comment