Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access non-numeric Object properties by index?

If I have an array like this:

var arr = ['one','two','three']; 

I can access different parts by doing this:

console.log(arr[1]); 

How can I access object properties by their order rather than by key?

Example:

var obj = {     'something' : 'awesome',     'evenmore'  : 'crazy' }, jbo = {     'evenmore'  : 'crazy',     'something' : 'awesome' }; 

How would I get the first property for each object–"something" from obj and "evenmore" from jbo–without explicitly using the property name?

Now, a few of you seem to think I'm after something like:

console.log(obj['something']); 

This is not the case, I'm specifically looking to target the index, just like the first example - if it's possible.

like image 429
daryl Avatar asked Oct 23 '11 13:10

daryl


People also ask

How do you access an object by index?

To get a value of an object by index, call the Object. values() method to get an array of the object's values and use bracket notation to access the value at the specific index, e.g. Object. values(obj)[1] . Copied!

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

Can object property be a 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.


1 Answers

"I'm specifically looking to target the index, just like the first example - if it's possible."

No, it isn't possible.

The closest you can get is to get an Array of the object's keys, and use that:

var keys = Object.keys( obj ); 

...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:

keys[ 0 ];  // 'evenmore' keys[ 1 ];  // 'something' 
like image 84
user113716 Avatar answered Sep 21 '22 23:09

user113716