Get value of first object property
17,302
Solution 1
var value = obj[Object.keys(obj)[0]];
Object.keys
is included in javascript 1.8.5. Please check the compatibility here http://kangax.github.io/es5-compat-table/#Object.keys
Edit:
This is also defined in javascript 1.8.5 only.
var value = obj[Object.getOwnPropertyNames(obj)[0]];
Reference:
Solution 2
function firstProp(obj) {
for(var key in obj)
return obj[key]
}
Author by
HP.
Updated on July 28, 2022Comments
-
HP. over 1 year
I have a simple object that always has one
key:value
likevar obj = {'mykey':'myvalue'}
What is the fastest way and elegant way to get the value without really doing this?
for (key in obj) { console.log(obj[key]); var value = obj[key]; }
Like can I access the value via index 0 or something?
-
Felix Kling over 10 yearsPlease note that the problem has nothing to do with JSON at all. It seems you are confusing JavaScript object literals (constructs of the JavaScript language syntax) with JSON (a language-independent data-exchange format, like XML or CSV). I will edit your question accordingly. See also: There is no such thing as a "JSON object".
-
Felix Kling over 10 years
-