Object Property Name as Number

Object property name as number

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

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

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.

Getting the object's property name

Use Object.keys():

var myObject = { a: 'c', b: 'a', c: 'b' };var keyNames = Object.keys(myObject);console.log(keyNames); // Outputs ["a","b","c"]

javascript object property name as decimal notation

The specification says:

PropertyName :
IdentifierName
StringLiteral
NumericLiteral

and shows that floats are fine in a NumericLiteral.

It's standard. Use it if you want to.

Using JSON Object Name if Object name is a number

You can programmatically get the value of the name by doing:

var objectNames = Object.keys(venue); // gives an array of the keys

Assuming you know there is only one:

var id = objectNames[0];

Then you can access the properties using id as others have shown.

Valid property names, property assignment and access in JavaScript

Short Answer

Object property names can be any valid identifier, numeric literal, or string literal (including the empty string).

With that said, there are some potentially confusing intricacies to keep in mind about JavaScript property names, as described below.

And unless you're working with valid (non-negative integer) array indexes, it's a good idea to explicitly assign all numerical property names as strings.

Negative Numbers

What might look like a negative number is actually an expression — something property names do not support.

// SyntaxError
const obj = { -12: 'nope' };

Fortunately, bracket notation handles expressions for us.

// Successful property assignment.
const obj = {};
obj[-12] = 'yup';

Typecasting

All property names are typecasted into strings before being stored.

const obj = {
12: '12'
};

console.log(typeof Object.keys(obj)[0]); // -> string

Parsing

But even before typecasting occurs, keys are parsed according to the syntax used, and transformed into a decimal literal.

const obj = {
// Valid string literal
'022': '022',

// Interpreted as decimal
6: '6',

// Interpreted as floating-point
.345: '0.345',

// Interpreted as floating-point
1.000: '1',

// Interpreted as floating-point
8.9890: '8.989',

// Interpreted as decimal
000888: '888',

// Interpreted as octal
0777: '511',

// Interpreted as hexadecimal
0x00111: '273',

// Interpreted as binary
0b0011: '3',
};

/* Quoted property name */
console.log(obj['022']); // "022"; as expected
console.log(obj[022]); // undefined; 022 is an octal literal that evaluates to 18 before our lookup ever occurs

/* Valid (non-negative integer) array index */
console.log(obj[6]); // "6"; as expected
console.log(obj['6']); // "6"; as expected

/* Non-valid array index */
console.log(obj[0x00111]); // "273"; we're accessing the property name as it was assigned (before it was parsed and typecasted)
console.log(obj['0x00111']); // undefined; after parsing and typecasting, our property name seems to have disappeared
console.log(obj['273']); // "273"; there it is, we found it using the evaluation of our original assignment

Numbers as properties on javascript object

Although here are already two good answers, I'd like to specifically address your question if you feel "paranoid" to use an array with many unfilled elements.

JS arrays are tricky as they may appear as "linear lists" as well as "dictionaries". If you use them as "dictionary", you are actually using JS Object properties. So you are mixing contents.

Try this:

var a = [];
a[10] = "the entry";
console.log("A seems to have a length of: " + a.length);

console.log ("Contents of a:");
for (var key in a) {
console.log("- key " + key + " has: " + a[key]);
}

Result:

"A seems to have a length of: 11"
"Contents of a:"
"- key 10 has: the entry"

There is actually only one element stored. This shows that length is just an information. It is an upper border that has been set in order to keep the array consistent, if it is seen as integer-addressed chain of elements. Here, length is not related to "size of memory allocated". There are no "empty storage places".

For some followup questions, you may try this change too:

var a = [];

a[5] = "the earlier entry";
a["the_key"] = "disturbing";
a["2015"] = "Top";

a[10] = "the entry";
console.log("A seems to have a length of: " + a.length);

console.log ("Contents of a:");
for (var key in a) {
console.log("- key " + key + " has: " + a[key]);
}

New result:

"A seems to have a length of: 2016"
"Contents of a:"
"- key 5 has: the earlier entry"
"- key 10 has: the entry"
"- key 2015 has: Top"
"- key the_key has: disturbing"

You can always use the Array context as well as the Object context.

This has consequences, e.g. for how to loop an array (it is already a huge discussion, jQuery's .each() adds some more questions :-) ).

With the classic for loop, you have to check if an element is undefined. (Remove the above key "2015" first).

for (var i=0; i<a.length; i++) {
console.log("at i=" + i + ": " + a[i]);
}

Shows:

"at i=0: undefined"  
"at i=1: undefined"
"at i=2: undefined"
"at i=3: undefined"
"at i=4: undefined"
"at i=5: the earlier entry" <<<
"at i=6: undefined"
"at i=7: undefined"
"at i=8: undefined"
"at i=9: undefined"
"at i=10: the entry" <<<

The object loop with in shows the keys.

Finally, it seems you have clarify the Array methods how they act for a linear array and if this is what you expect. indexOf(), for example, acts like for a linear array. indexOf() is defined for Array, not for Object. Therefore indexOf() won't return you an alphanumeric key but only linear index positions.

http://www.javascripture.com/Array

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

Get object property name as a string

Yes you can, with a little change.

function propName(prop, value){
for(var i in prop) {
if (prop[i] == value){
return i;
}
}
return false;
}

Now you can get the value like so:

 var pn = propName(person,person.first_name);
// pn = "first_name";

Note I am not sure what it can be used for.

Other Note wont work very well with nested objects. but then again, see the first note.

Access object property which is a number

You convert multiple arrays to an object with the following code:

$obj1 = (object) ['name' => 'Jan', 'job' => 'IT'];
$obj2 = (object) ['name' => 'Adam', 'job' => 'PR'];
$obj3 = (object) ['name'=> 'Wojtek', 'job' => 'IT'];
$obj4 = (object) ['name' => 'Marcin', 'job' => 'Car'];
$obj = (object) [$obj1, $obj2, $obj3, $obj4];

To get the name of the first object you can cast the object to an array (solution for PHP < 7.2):

echo ((array) $obj)[0]->name; // Jan
echo ((array) $obj)[1]->name; // Adam

Since PHP 7.2 you can also access numeric property names too:

echo $obj->{0}->name; // Jan
echo $obj->{1}->name; // Adam

complete example (with demo):

$obj1 = (object) ['name' => 'Jan', 'job' => 'IT'];
$obj2 = (object) ['name' => 'Adam', 'job' => 'PR'];
$obj3 = (object) ['name'=> 'Wojtek', 'job' => 'IT'];
$obj4 = (object) ['name' => 'Marcin', 'job' => 'Car'];
$obj = (object) [$obj1, $obj2, $obj3, $obj4];

//your output
var_dump($obj);

//PHP < 7.2: get the output of the name of the first object.
echo 'Test: '.((array) $obj)[0]->name; // Jan

//or since PHP 7.2
echo $obj->{0}->name; // Jan

demo: https://3v4l.org/kIVuS



Related Topics



Leave a reply



Submit