snippetjavascriptCritical
How to loop through a plain JavaScript object with the objects as members
Viewed 0 times
plainhowobjectwiththeobjectsmembersloopthroughjavascript
Problem
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)?
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"
}
}Solution
for (var key in validation_messages) {
// 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]);
}
}Code Snippets
for (var key in validation_messages) {
// 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]);
}
}Context
Stack Overflow Q#921789, score: 2264
Revisions (0)
No revisions yet.