FoobarisMaximus FoobarisMaximus - 1 year ago 98
Javascript Question

JavaScript: Get first and only property name of object

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
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;

Answer Source

Maybe Object.keys can work for you. If its length returns 1, you can use yourObject[Objects.keys[0]] to get the only property of the object. The MDN-link also shows a custom function for use in environments without the keys method1. Code like this:

var obj = {foo:'bar'}, 
    kyz = Object.keys(obj);
if (kyz.length === 1){
   alert(obj[kyz[0]]); //=> 'bar'
} else {
  /* loop through obj */

1 Some older browsers don't support Object.keys. The MDN link supplies code to to make it work in these browsers too. See header Compatibility in the aforementioned MDN page