How To Write Nested Property From An Object – Javascript

Javascript is an object orientated programming language. For Object Orientated programming language, being able to store information in an object is a very important feature. Being able to store information in an object provide the flexibility in handling data and categorizing information as necessary.

It would be a lot simpler to define the information to an object and give the object many levels and structure the object in a way that we would desire. Nevertheless, when it come to getting back the information from the object and if the object has many levels, how are we going to process the data that stored inside the object? It would be a lot more complicated if this process is automatic and we do not know the structure of this object.

This small tutorial and the example script will show you how to deal with a multilayer object. I will also write down the small procedures of it.

When dealing with a multi-layer object and we do not know the structure of it, the first obstacle that we would have is not knowing the name of the property. We then would not know which property is nested and of which is not nested. Thus we have to automate the process so we can get to the deepest layer of the object. Our problem for this scenario would be, how to detect which property within the object is another object and if so how do we automatically access that property and if the object has any more child object, how do we process all the child object.

Scenario:

  1. Access object within object until it is the last layer
  2. If the first layer have more than one object property, being able to access all the object’s property

Problem:

  1. Automatically detect if the child of the main object is an object and reinitialise the script without needing to declare a property name or method.

Procedures:

With the above problem the procedures would be: “read property of the object => detect property(ies) that are object(s) within the original object => recalling the function on those properites that are sub-child of the main object(s) => this loop through infinity until there the last layer of object is processed.

To translate the procedures to code, I will demonstrate the below in a function call.

function x(obj){
   for ( var n in obj) {
      if ( typeof (obj[n]) !== "object") {
         // Do something
      }   
   
      if ( typeof(obj[n]) === "object" ){
          x(obj[n]); // I am recalling myself
          // Maybe do something else too     
      }
   }
}

This code below is an example of the above procedures, it can be modified to work with any type of data as desired. What does this function take as an input? The function takes in an object or array as the input value for the first input value, the second is the name of the array in string format. You do not have to specify the name of the Array here.

This function will write the structure of the object, and all the properties and properties’ children. This function also print out the level of each property and organize the properties neatly. The writing format is in HTML. This script does not return any value after execution. Most of the explanation to how the program work was written into the comment of the code snippet.

Advertisement

function writeNestedProperty(obj, objName){
/* This sample function is written by kevinhng86 from FAI Hosting Solution.
 * A copy of this can be found on http://kevinhng86.iblog.website 
 *  
*/

/* Define a name for object if there is not an input for object Name.
 * To use this function give it an object and the name of the object
 */
    if (!objName && typeof(objName) !== "string") objName = "No Name Object"; 

    // Depend on what language you use this the line break character
    var linebreak = "<br />";
    
    // This is the separator between property
    var separator = " | ";
        // Writing the header 
        document.write("<b>"+objName+"</b>");
        document.write(linebreak);
        document.write(linebreak); 
        document.write(linebreak); 
        document.write("<b><font color=red>"+"main"+"</font></b>");
        document.write(linebreak);
    
    // This is the main function that will write the information contain in the object 
    function z(obj, idx, propname){
    // This is to set the nested level of the object as 1 is the first level. This is for writing
    // When it is frist run it will set it to 1. Any subsequense run will be define below.
    if (!idx) var idx = 1;
    
    /* This array propname is to store the name of the object or array the script currently working on
     * This will get pass to the function when it is recursively call.
     * Else since we start at level one we have to skip the 0 position for this array.
     */
    if (!propname) var propname = ["","main"] ;
    

    // First for sorting it will deal with anything that is not an object
    for (var name in obj){
        if ( typeof (obj[name]) !== "object"){
          document.write("Property Name: " + name);
          document.write(linebreak);
          document.write("Property Value: " + obj[name]);
          document.write(linebreak+linebreak);
      //  delete(obj[name]); // Delete is unnecessary however for some other scripting language this will help rid of extra memory
          }                     // The main problem that I encounter with Javascript is when you delete an object that sent in to a function
                               // For some reason it will also delete the main reference of it. So becare full when use this
    }
    
    /* After writing anything that is not an object or array.
     * The script execute a second time on anything else that is object or array.
     * For sorting purpose you can make 3 loop. 
     * Anything that is not object to run first like the above.
     * A loop for anything that is instanceof Object but not an instanceof Array.
     * A third loop run for anything is instanceof Array.
    */
    for (var name in obj){
      if ( typeof(obj[name]) === "object" ){
           /* When an object is found within the property of the main object.
          * idx variable is increase by one to keep count of the nesting level. since this script return nothing.
            * Property name of the object currently working on is store into array propname at the position that idx defined
          */
         idx = idx + 1;
         propname[idx] = name;
         
         /* This code block is for writing Nested level name  */
         document.write('<font color=blue><b>Nested level: ' + idx+ '</b></font>');
         document.write(linebreak);
         // This below is to write the parent of the object currently working on;
         document.write('<b><font color="red">'+name+'</font> is child of <font color="red">'+propname[idx - 1]+"</font></b>");
                  
         // If we working deep beyond the first level this will continue writing the parent of the parent of this object.      
          // We take out two level because the above already write that two level
          for ( i = idx; i > 2; i--){
             document.write('<b> is child of <font color=red>' + propname[i - 2] + '</font></b>');
         }       
         document.write(linebreak);
         /* End writing code block */
         
         
         /* Sending this object into this function again and run it. 
          * If you been following through with what the script do until now.
          * You will know the procedure of what it is going to do
          * It will keep on doing this until there is no layer of object left.
          */
         z(obj[name], idx, propname); 
         /* The instance the script exit from any subseqense self initialise, it will have to minus the idx count.*/
         idx = idx - 1;
        } 
    }
    
    
} //End function z
  /* This is to initilize the call when the object first come in. */
  z(obj);
  /* Once everything is done this script return null. This would be a void function in other language. */
  return ;
}

// Test case for trying out this script.
var test =  {
             this: "cool",
             me: "lovely",
             okay2: {there: "is", a: "quick brown fox", c: {abc:"abc", D: {d:"love", a: "war"} }},
             okay: {there: "is", a: "quick fox"},
             well: ["very", "abc", "def", "ghi",["viva", "okay", "notokay" ]],
 

            };
writeNestedProperty(test, "test");

This post was written by Kevin and was first post @ http://kevinhng86.iblog.website.
Original Post Name: "How To Write Nested Property From An Object – Javascript".
Original Post Link: http://kevinhng86.iblog.website/2017/01/17/write-nested-property-of-an-object-javascript/.

Advertisement


Random Article You May Like

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*