I have an object and I want to access the first element of that object, so first, I need to get the first key of that object. I have two ways to do it but I'm looking for a better way.
The first is:
var firstKey = Object.keys(myObject)[0];
but Object.keys
will return an array of all the keys. So if I want just the first key, this method will be too expensive for my quest (especially if myObject
have too many keys).
The second method is:
var firstKey = null;
for(var key in myObject){
firstKey = key;
break;
}
this works just fine and it's better than the first one but I think it's hideous (for
, break
and all that mess just to get the first key).
So
I was wondering if there is a much elegant way to get the first key? Something like:
var firstKey from myObject;
EDIT:
I don't care about the ordering I just want to get whatever the first key is.
EDIT2:
I have an object that holds some informations (lets say, for example, a person's name is a key, his email will be the value). Let's say I have a placeholder where some name and it's email adress are printed. If I press delete, I delete that entry (delete myObject[name];
), then I need to fill that placeholder with another name and email (I don't care who anyone will do), so the first (or whatever the first is now) will do.