views:

954

answers:

3

Say you have a javascript object like this:

var data = { Name: 'Property Name', Value: '0' };

You can access the properties by the property name:

var name = data.Name;
var value = data["Value"];

But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?

In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.

My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.

+3  A: 
for(var property in data) {
    alert(property);
}
karim79
+7  A: 

You can loop through keys like this:

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

This alerts "Name" and "Value". As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:

for each(var value in data){
  alert(value);
}

This example loops through values, so it would alert "Property Name" and "0".

Ron DeVera
+1  A: 

You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
         if(this.hasOwnProperty(p)){
          A[A.length]= p+'='+this[p];
         }
        }

    return A.join(', ');
}
kennebec