Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of first object property

I have a simple object that always has one key:value like var 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?

like image 468
HP. Avatar asked Oct 02 '13 13:10

HP.


2 Answers

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:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Enumerating_all_properties_of_an_object

like image 134
thefourtheye Avatar answered Sep 30 '22 05:09

thefourtheye


function firstProp(obj) {
    for(var key in obj)
        return obj[key]
}
like image 22
georg Avatar answered Sep 30 '22 06:09

georg