JavaScript: Get first and only property name of object

Viewed 53615

If I want to enumerate the properties of an object and want to ignore prototypes, I would use:

var instance = { ... };

for (var prop in instance) {
    if (instance.hasOwnProperty(prop)) {
        ... 
    }
}

What if instance only has one property, and I want to get that property name? Is there an easier way than doing this:

var instance = { id: "foobar" };

var singleMember = (function() {
    for (var prop in instance) {
        if (instance.hasOwnProperty(prop)) {
            return prop;
        }
    }
})();
7 Answers
  var foo = {bar: 1};
  console.log(Object.keys(foo).toString());

which will print the string

"bar"

This is an old post, but I ended up writing the following helper function based on Object.keys().

It returns the key and value of the first property.

getFirstPropertyKeyAndValue(sourceObject) {
    var result = null;
    var ownProperties = Object.keys(sourceObject);
    if (ownProperties.length > 0) {
      if (ownProperties.length > 1) {
        console.warn('Getting first property of an object containing more than 1 own property may result in unexpected results. Ordering is not ensured.', sourceObject);
      }
      var firstPropertyName = ownProperties[0];
      result = {key: firstPropertyName, value: sourceObject[firstPropertyName]};
    }
    return result;
  }

Answers in here all good, and with the caveat that the order may be unreliable (although in practice it seems the order the properties are set tends to stay that way), this quick and dirty method also works:

var obj = {foo: 1, bar: 2};
for(var key in obj) {
  //you could use key here if you like
  break;
}
//key now contains your first key

or a shorter version should also do it:

for(var key in obj) break;
//key now contains your first key
Related