I ran into an interesting predicament on a project.

I needed to get a specific key out of a JSON object. I wanted to do this without having to resort to a for-in loop. I needed this because I have functions that are stored in an array, the functions are then called by a specific key name and passed a value.

Sample of functions:

var function_col = {  
  foo : funciton( val ){ console.log( val + "foo" ) } // Log [val]foo
, bar : function( val ){ console.log( val + "bar" ) } // Log [val]bar
}

The above function_col object contains the keys foo and bar. In my scenario, these methods are called dynamically. I’m not going to test against them using a conditional statement.

Let’s say, I have a file that gets dynamically generated, it contains a set of calls my code wants to make.

Here’s an example:

var obj = { "foo" : "value" } // Call function foo  

I need to parse the key out of that object. Here’s what I would have done in the past.

var key;

for( key in obj ) break;  
// use key
function_col[ key ].call( this, obj[ key ] ); // call the function that contains the key.  

I hate this option. Enter Object.keys, a much cleaner way to do it.

var key = Object.keys( obj )[ 0 ] // Returns an array of keys, It will always be one key.  
function_col[ key ].call( this, obj[ key ] );  

Object.keys is awesome, it’s a great helper function that gives you a collection of enumerable properties in your object.

Here’s a console.log of the obj variable.

console.log( obj );  
// [ 'foo' ]