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; } } })();
To get object property name with JavaScript, we use the Object. keys method. const result = Object. keys(myVar); console.
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] .
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] .
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.
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With