Access to non-numeric object properties by index?

If I have an array like this:

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

I can access the various parts by following these steps:

 console.log(arr[1]); 

How can I access the properties of an object in their order, and not by key?

Example:

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

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

Now, some of you seem to think I'm behind something like:

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

This is not the case, I am specifically targeting the index, as in the first example - if possible.

+42
javascript arrays
Oct 23 '11 at 13:00
source share
5 answers

"I specifically plan to target the index, as with the first example - if possible."

No, It is Immpossible.

The closest thing you can get is to get an array of object keys and use it:

 var keys = Object.keys( obj ); 

... but there is no guarantee that the keys will be returned in the order you specified. So it might look like this:

 keys[ 0 ]; // 'evenmore' keys[ 1 ]; // 'something' 
+69
Oct 23 '11 at 13:10
source share

The only way I can do this is to create a method that gives you a property using Object.keys(); .

 var obj = { dog: "woof", cat: "meow", key: function(n) { return this[Object.keys(this)[n]]; } }; obj.key(1); // "meow" 

Demo: http://jsfiddle.net/UmkVn/

You could extend this to all objects using Object.prototype; but this is usually not recommended.

Use the helper element of the function instead:

 var object = { key: function(n) { return this[ Object.keys(this)[n] ]; } }; function key(obj, idx) { return object.key.call(obj, idx); } key({ a: 6 }, 0); // 6 
+34
Oct 24 2018-11-11T00:
source share
 var obj = { 'key1':'value', '2':'value', 'key 1':'value' } console.log(obj.key1) console.log(obj['key1']) console.log(obj['2']) console.log(obj['key 1']) // will not work console.log(obj.2) 

Edit:

"I specifically plan to target the index, as with the first example - if possible."

In fact, the "index" is the key. If you want to keep the key position, you need to create a custom object to process it.

+2
Oct 23 2018-11-11T00:
source share

If you are not sure if Object.keys () will return the keys in the correct order, you can try this logic instead

 var keys = [] var obj = { 'key1' : 'value1', 'key2' : 'value2', 'key3' : 'value3', } for (var key in obj){ keys.push(key) } console.log(obj[keys[1]]) console.log(obj[keys[2]]) console.log(obj[keys[3]]) 
0
Jan 30 '15 at 14:10
source share

jquery you can do this:

 var arr = $.map(obj,function(value, key) { return value; }); alert(obj[0]); 
0
May 26 '17 at 18:40
source share



All Articles