Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object property name as 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.

Like so:

me = {     name: "Robert Rocha",     123: 26,     origin: "Mexico" } 

My question is, how do you reference the property that has an integer as a name? I tried the usual me.123 but got an error. The only workaround that I can think of is using a for-in loop. Any suggestions?

like image 343
Robert Rocha Avatar asked Jun 04 '13 01:06

Robert Rocha


People also ask

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.

Can object key be a number?

Each key in your JavaScript object must be a string, symbol, or number.

How do I find the name of an object property?

To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.


2 Answers

You can reference the object's properties as you would an array and use either me[123] or me["123"]

like image 70
Tom Avatar answered Sep 18 '22 08:09

Tom


Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence. For all other property names, you must use bracket notation.

In an object literal, the property name must be an identifier name, string literal or numeric literal (which will be converted to a string since property names must be strings):

var obj = {1:1, foo:'foo', '+=+':'+=+'};  alert(obj[1] + ' ' + obj.foo + ' ' + obj['+=+']); // 1 foo +=+ 
like image 21
RobG Avatar answered Sep 21 '22 08:09

RobG