The easiest way to access an object's single own property?

送分小仙女□ 提交于 2019-12-29 02:14:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!