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.
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!
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] .
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.
"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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With