Can I get a javascript object property name that starts with a number?

var myObj = {"suppliers":[{"name":"supplier1","12m":"0.08","24m":"0.06"}]};

alert(myObj.suppliers[0].12m);

Is there a different way to get this property, or should I just not use a key that starts with a number?


Solution 1:

You can use the following syntax to do what you describe using bracket notation:

myObject["myProperty"]

Bracket notation differs from dot notation (e.g. myObject.myProperty) in that it can be used to access properties whose names are illegal. Illegal meaning that with dot notation, you're limited to using property names that are alphanumeric (plus the underscore _ and dollar sign $), and don't begin with a number. Bracket notation allows us to use a string to access a property and bypass this.

myObject.1 // fails, properties cannot begin with numbers
myObject.& // fails, properties must be alphanumeric (or $ or _)

myObject["1"] // succeeds
myObject["&"] // succeeds

This also means we can use string variables to look up and set properties on objects:

var myEdgyPropertyName = "||~~(_o__o_)~~||";

myEdgyObject[myEdgyPropertyName] = "who's there?";

myEdgyObject[myEdgyPropertyName] // "who's there?";

You can read more about dot and bracket notation here, on MDN.

Solution 2:

Yes, use bracket syntax:

alert(myObj.suppliers[0]["12m"]);

From MDN

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).