JavaScript: Get first and only property name of object

Maybe Object.keys can work for you. If its length returns 1, you can use yourObject[Object.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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)