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?

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1
function firstProp(obj) {
    for(var key in obj)
        return obj[key]
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.