hey guys i am new to javascript and Jquery in general , and i am facinated by the usage of Object literals so far . now i was going through the source of bootstrap modal.js plugin and came across the following lines of code :
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
you can checkout this line of code on git too.
now that line of code is creating a pretty complex object literal something that has a lot of 'Object' inside 'Object' inside 'Object' and so on .. basically a nested object literal .
in order for me to totally understand that line of code its essential that i am be able to console.log the object literal.
i saw a thread on SO here.
now the solution i see in that answer to print out an Object literal is as follows :
for (var key in validation_messages) {
if (validation_messages.hasOwnProperty(key)) {
var obj = validation_messages[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
alert(prop + " = " + obj[prop]);
}
}
}
}
now that solution works fine , if i have a object literal as follows :
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
but what if i have a object literal like the follows :
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": {
"first_name" : "Ratan",
"secound_name" : "Tata",
},
"your_msg": "foo equals bar"
}
}
i will get the following in the console :
"your_name = jimmy"
"your_msg = hello world"
"your_name = [object Object]"
"your_msg = foo equals bar"
the problem is everytime the value of a key is an object , i want the loop to enter the object and print the key and values from there too , basically i want this to be recursive . i tried modifying the original code of what i found in that thread , but i barely know what i am doing . below is the code that i modified .
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": {
"first_name" : "Ratan",
"secound_name" : "Tata",
},
"your_msg": "foo equals bar"
}
}
for (var key in validation_messages) {
if (validation_messages.hasOwnProperty(key)) {
var obj = validation_messages[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(typeof prop != 'string') {
for(var obj_key in prop) {
var obj = prop[obj_key];
for (var prop in obj){
console.log(prop + " = " + obj[prop]);
}
}
}
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
}
To repeat my question , its very essential for me to understand how to recursively go through a object literal and print out its properties .
my idea of the object literal data displaying is as follows :
.
Thank you.
Alexander.