0

When I need to get the key (string) from an javascript Object, I use:

for (var key in foo) {
    console.log(key)
}

This will log all the key strings in the console.

However what if there is only 1 entry in the array? (so only 1 key)

I can't find how to handle that?

The above for works but not sure if it's needed when there is only 1 element?

I don't want to log the object associated, I want to log the string of the key itself.

On an object { fruit : 'apple' } I want to log the string "fruit"

So considering var foodType = { fruit : 'apple' , meat: 'beef' , fruit : 'pear' }

And also if there is only one element

foodType = { fruit : 'apple' }

How do I log that?

2
  • Ehhhh ... I read the question 3 times and I still don't know whats asked. Commented Oct 10, 2013 at 11:20
  • I don't think it's key. First, because JS got only integers as keys in arrays. Second, because you are getting values, not keys. Commented Oct 10, 2013 at 11:20

2 Answers 2

3

You might consider something like:

var obj = { foo: "bar" };
var key = Object.keys(obj)[0]; // "foo"
var value = obj[key]; // "bar"

Or in one line:

var value = obj[Object.keys(obj)[0]]; // "bar"
Sign up to request clarification or add additional context in comments.

7 Comments

+1 Pretty good, even if the one-liner is pretty cryptic for a junior dev like myself :|
I think it's along the right track, but value doesn't equal the key, it equals the object {key : value} I want value = key(string) so value should = 'key'
I don't understand what you mean.
I don't want to log the object associated, I want to log the string of the key itself. { 'fruit' : 'apple' } I want to log the string 'fruit'
Then just use Object.keys(obj)[0].
|
1

One possible solution:

var key = Object.keys(foo).pop();

2 Comments

Whats the difference if foo has 1 or 100 properties ?
@jAndy This might be slower :) Otherwise it is just a way to get the last key in one line, exactly what the OP wants to get instead of for (var key in foo) break;.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.