2

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 :

data structure.

Thank you.

Alexander.

Community
  • 1
  • 1
Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

1 Answers1

1

As pseudo code, the solution is pretty straight-forward :

function objectToString(object) {
  string result = '';
  for (key in object) {
    if (hasFields(object[key]))
      result  += objectToString(object[key]);
    else 
      result  += key + ':' + object[key];
  }
}

The extra difficulty here is managing the presentation. One way to do so is to introduce an indentation level. This level can then be incremented on each call in order to get the tree representation you seek.

In JS, you may have code like this :

function objectToString(object, level) {
  var prettyString = '',
      tabs = '';
  // We prepare the indentation for the current object
  for (var i=0; i<level; i++) {
      tabs += '\t';
  }

  for (var key in object) {
    prettyString += tabs + key;
    // if the considered field is an object, we call this function with a 
    // greater indentation level
    if (typeof object[key] === 'object') {
      prettyString += '\n';
      prettyString += prettyPrintKeys(object[key], level + 1);
    } else {
      prettyString += ':' + object[key] ;
    }
    prettyString += '\n';
  }
  return prettyString;
}

This function can be used on your example like this : objectToString(validation_messages, 0);

However, please note that while this code is simple and good for seeing recursion in JS, it is not complete. Should you wish to have a more robust (and generic) solution, you may want to inquire about the JSON format.

Community
  • 1
  • 1
merours
  • 4,076
  • 7
  • 37
  • 69