Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

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;
        }
    }
})();
question from:https://stackoverflow.com/questions/6765864/javascript-get-first-and-only-property-name-of-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 method(1)

. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...