0

Possible Duplicate:
Access the first property of an object

I just want to know if there is a better way to get the first member name in a object like:

var x={a:1};
func(x);//will return 'a'

I programmed a small function but I'm not satisfied, i think that there is a better way

what i did is :

var get_member = function(obj){for (i in obj){if (obj.hasOwnProperty(i)) return i;}};
Community
  • 1
  • 1
Hilmi
  • 3,207
  • 6
  • 24
  • 54

3 Answers3

0

Supposing your "first member" is defined by addition order :

There is no guaranteed order in javascript object properties, so you shouldn't do this even while it currently work on most browsers.

Look at this related question : Elements order in a "for (… in …)" loop

So the proper ECMAScript compliant implementation for first added member can't exist.

Supposing you have an intrinsic "first member" definition based on key (or value) :

If what you want is based on a given order, let's say alphabetical for example, you can do this :

var keys = [];
for (k in x) {
   keys.push(k);   
}
keys.sort();
return keys[0];
Community
  • 1
  • 1
Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
0

There is no "first" property of an object, they have no order. You can only get "some" property by using

function func(obj) {
    if (Object(obj) !== obj)
        throw new Error("not an object");
    for (var prop in obj)
        return prop;
    return null;
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

I think it's the better way to get the first key from the object.

var x= {a:1};

for (var key in x) break;

console.log(key);

kannanrbk
  • 5,894
  • 11
  • 46
  • 84