问题
I have an object which will only have one property (own property). What is the easiest way to access that property's value?
Something like:
value = obj[<firstProperty>];
I know I can write a function or a for loop to do this but am asking if there is a shorter way.
for (p in obj) {
if (obj.hasOwnProperty(p)) {
value = obj[p];
}
}
I won't know the name of the property up front. I only know that there will only be one property directly on the object.
回答1:
something like
var value = obj[ Object.keys(obj)[0] ];
getting the keys with Object.keys
and the first (and only) key with [0]
回答2:
This should work.
var keys = Object.keys(obj);
var value = obj[keys[0]];
We can make it shorter
var value = obj[Object.keys(obj)[0]];
来源:https://stackoverflow.com/questions/29439905/the-easiest-way-to-access-an-objects-single-own-property