Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

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

1 Answer

something like

var value = obj[ Object.keys(obj)[0] ];

getting the keys with Object.keys and the first (and only) key with [0]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...