1

In PHP, we can loop through an associative array, and get the values of both the key and the value like this:

$myArray = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

foreach($myArray as $key => $val){
    echo 'The value of "'.$key.'" is "'.$val.'".\n';
}

/* Output:
The value of "key1" is "value1".
The value of "key2" is "value2".
*/

Is there any way this can be done in javascript?

myObject = { 
    'key1': 'value1',
    'key2': 'value2'
};

for (val in myObject) {
    // check hasOwnProperty and what not...

    // Now, how do I get the key value?
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object – ScottE Aug 23 '11 at 14:56

2 Answers2

4

Your question has a concept reversed: JavaScript's for/in loop gets you the key, not the value. You then obtain the value by using the key.

var myObject = { 
        'key1': 'value1',
        'key2': 'value2'
    },
    key,
    val;

for( key in myObject )
{
    if( Object.prototype.hasOwnProperty.call( myObject, key ) )
    {
       val =  myObject[key];
    }
}
JAAulde
  • 19,250
  • 5
  • 52
  • 63
2

That's easy, using myObject[val]

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308