javascript tutorial - [Solved-5 Solutions] Loop through all members in a JavaScript - javascript - java script - javascript array



Problem:

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

Solution 1:

var validation_messages = {
    "key_1": {
        "your_name": "jimmy",
        "your_msg": "hello world"
    },
    "key_2": {
        "your_name": "billy",
        "your_msg": "foo equals bar"
    }
}

click below button to copy the code. By JavaScript tutorial team

Solution 2:

    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if(!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}



click below button to copy the code. By JavaScript tutorial team

Solution 3:

var obj = {
    first: "John", 
    last: "Doe"
};

//
//  Visit non-inherited enumerable keys
//
Object.keys(obj).forEach(function(key) {

    console.log(key, obj[key]);

});

click below button to copy the code. By JavaScript tutorial team

Solution 4:

The problem with this

for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}
click below button to copy the code. By JavaScript tutorial team

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) {
         if (obj.hasOwnProperty(prop)) {
            alert(prop + " = " + obj[prop]);
         }
      }
   }
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

Using ’ Underscore.jss _.each:

_.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
        console.log(value);
    });
});
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Loop through all members in a JavaScript