Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 233
bodine Avatar asked Apr 27 '11 19:04

bodine


People also ask

Can JS object key start with number?

operator to access the key then the key must be a valid identifier which means they can not begin with a number or contain space.

Can object property name be number?

According to the official JavaScript documentation you can define object literal property names using integers: Additionally, you can use a numeric or string literal for the name of a property.

Can JavaScript object property be a number?

Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.

How do you get the properties name of an object in typescript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .


2 Answers

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.

like image 87
mattsven Avatar answered Sep 30 '22 18:09

mattsven


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).

like image 22
cmd Avatar answered Sep 30 '22 19:09

cmd