tags:

views:

55

answers:

2

I'm trying to write a function that needs to know the property names of an object being passed in, like so:

var data = { "key1":"value1", "key2":"value2", etc}
               ^ i want the string value "key1"

How do I retrieve the string "key1" from data? I know I can set a property dynamically like data[prop]=value but i want to know what prop is from an object passed in.

If that doesn't make sense I suppose I could try to explain more. Thanks!

I eventually want to do something like:

for (var i = 0; i<data.length; i++)
{
    var name = data[i].getPropertyName() <--- not a real function
    // do stuff
}
+2  A: 
var data = { "key1":"value1", "key2":"value2", etc}

for (prop in data) {
  var propertyName = prop;
  // do something with your new propertyName
}

Yeah, it's that simple.

Robusto
+7  A: 
T.J. Crowder
thank you for this thorough answer!
Jason
@Jason: No worries, glad that helped!
T.J. Crowder