views:

8835

answers:

5

How can I loop through all members in a JavaScript object including values that are objects.

For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?

var validation_messages = {
    "key_1": {
     "your_name": "jimmy",
     "your_msg": "hello world"
    },
    "key_2": {
     "your_name": "billy",
     "your_msg": "foo equals bar"
    }
}
+1  A: 
for(var k in validation_messages) {
    var o = validation_messages[k];
    do_something_with(o.your_name);
    do_something_else_with(o.your_msg);
}
chaos
+18  A: 
for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}
AgileJon
works like a charm!
gack! please change the alert so it's not inside each loop!!!!! use console.log (for firebug), or concatenate a bunch of strings and call alert once. Otherwise you get a series of modal dialog boxes that keep on coming if there are a lot of validation_messages.
Jason S
@Jason S: I don't think that alert is meant for production code. :-)
Nosredna
+1  A: 
for(var key in validation_messages){
    for(var subkey in validation_messages[key]){
        //code here
        //subkey being value, key being 'yourname' / 'yourmsg'
    }
}
Dmitri Farkov
Maybe I'm doing something wrong, but this example doesn't work for me.
needs a "var" to prevent clobbering global variables of the same name
Jason S
+2  A: 

If you use recursion you can return object properties of any depth-

function lookdeep(obj){
    var A= [], tem;
    for(var p in obj){
     if(obj.hasOwnProperty(p)){
      tem= obj[p];
      if(tem && typeof tem=='object'){
       A[A.length]= p+':{ '+arguments.callee(tem).join(', ')+'}';
      }
      else A[A.length]= [p+':'+tem.toString()];
     }
    }
    return A;
}

var O={a: 1, b: 2, c:{c1: 3, c2: 4, c3:{t:true, f:false}},d: 11};

var s=lookdeep(O).join('\n');
alert(s)



/*  returned value: (String)
a:1
b:2
c:{ c1:3, c2:4, c3:{ t:true, f:false}}
d:11
*/
kennebec
+5  A: 

The problem with this


for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

is that you'll also loop through the primitive object's prototype.

With this one you will avoid it:


for (var key in validation_messages) {
   if (validation_messages.hasOwnProperty(key)) {
     var obj = validation_messages[key];
     for (var prop in obj) {
       alert(prop + " = " + obj[prop]);
     }
   }
}
Chango