Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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;         }     } })(); 
like image 225
FoobarisMaximus Avatar asked Jul 20 '11 17:07

FoobarisMaximus


People also ask

How do I find the name of an object property?

To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.

How do I find the first item of an object?

To access the first property of an object, pass the object to the Object. values method and access the element at index 0 , e.g. Object. values(obj)[0] .

How do you get the properties name of an object in typescript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How can you get the list of all properties in an object in JavaScript?

To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.


2 Answers

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

like image 159
KooiInc Avatar answered Sep 23 '22 06:09

KooiInc


Shortest form:

instance[Object.keys(instance)[0]]; 

ES6+ function:

let first = v => v[Object.keys(v)[0]]; 

Use the function:

first({a:'first', b:'second'}) // return 'first' 
like image 31
Isaac Han Avatar answered Sep 20 '22 06:09

Isaac Han