8

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
HP.
  • 19,226
  • 53
  • 154
  • 253
  • 2
    Please 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"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Felix Kling Oct 02 '13 at 13:42
  • 1
    *related*: [JavaScript: Get first and only property name of object](http://stackoverflow.com/questions/6765864/javascript-get-first-and-only-property-name-of-object) – Felix Kling Oct 02 '13 at 13:46

3 Answers3

25
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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1
function firstProp(obj) {
    for(var key in obj)
        return obj[key]
}
georg
  • 211,518
  • 52
  • 313
  • 390
0

You can use Object.values()

const obj = {
  myKeyA: 'my value A',
  myKeyB: 'my value B',
}

const [valueOfFirstObjectProperty] = Object.values(obj)

console.log('Value:', valueOfFirstObjectProperty) // my value A
SandroMarques
  • 6,070
  • 1
  • 41
  • 46