2

I have an object like this:

var foo = { 'bar' : 'baz' }

bar can be any word, I need to read baz. Since the object is always like this (one row) I find making an each cycle inefficient.

$.each( body.message, function( key, value ) { 
  alert(value);
} 

Is there an smart way of doing this?

DomingoSL
  • 14,920
  • 24
  • 99
  • 173
  • 1
    "Inefficient" how? As in, ugly code? Inefficient to type out? Actual CPU performance is not something you need to worry about (unless you're doing this 1000 times a second, at which point you might have other issues in your design :p). – cloudfeet Nov 25 '14 at 17:07
  • as of JavaScript 1.8.5 you can use Object.keys(obj) – Software Engineer Nov 25 '14 at 17:11
  • @Engineer Dollery et al: This was not a duplicate of that question as the OP only wants a specific (first) property name. The answers on the dupe are not appropriate. Scimonster's answer below is appropriate. – iCollect.it Ltd Nov 26 '14 at 10:19

3 Answers3

3

Use Object.keys() to list the keys, and get it from there.

foo[Object.keys(foo)[0]]
Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

You can also just use a for loop: http://jsfiddle.net/TrueBlueAussie/s2745674/1/

var foo = { 'bar' : 'baz' }

for (var key in foo)
{
    alert(key);
}

For a single item (as specified) you won't notice a speed decrease (heck for loads of items you would notice it) :)

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
0
var foo = { 'bar' : 'baz' };

for(var key in foo)
{
    if (foo.hasOwnProperty(key)){
         // use key for the key and foo[key] for the value.        
         console.log('key: ' + key + ' value: ' + foo[key]); // key: bar value: baz
    }
}
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99