views:

48

answers:

1

Hi there.

I am trying to create a function which,

When given an object will output something like

<div>
 reason : ok
 status : 0
 AiStatistics : null
 CurrentSeasonArenaStatistics : null
 <div>
  Player
  <div>
   CampaignProgressCoop : CompletedLegendary
   CampaignProgressSp : PartialHeroic
   <div>
    ReachEmblem
    <div>
     background_index : 2
     change_colors : [0,7,2,0]
     flags : 0
     foreground_index : 49
    </div>
   </div>
  </div>
 </div>
 gender : male
</div>

How would i go about this?

This is my attempt:

function read_object(object){
  var $obj = $('<div />');
  for(var o in object) {
    $obj.append(o+' : ');
    if(typeof(object[o]) == 'object' and object[o] != null) {
      $obj.append(read_object(object[o]));
    }
    else
      $obj.append(object[o]);
  }
  return $obj;
}

Here is the object i am using

{
  "reason":"Okay",
  "status":0,
  "AiStatistics":null,
  "CurrentSeasonArenaStatistics":null,
  "Player":
  {
    "CampaignProgressCoop":"CompletedLegendary",
    "CampaignProgressSp":"PartialHeroic",
    "ReachEmblem":
    {
      "background_index":2,
      "change_colors":[0,7,2,0],
      "flags":0,
      "foreground_index":49
    }
  }
}
A: 

Seperate the method out from the main call.


function read_object(object){
  //do some cool stuff to return a string
  return str;
}
function loopy(object){
    for(var o in object) {
        if(typeof(object[o]) == 'object'){
            read_object(object)
        }else{
            //output in some other way
        }
    }
}
Kieran
@KieranNo matter what you do you would end up with a recursive pattern.In your example you would just end up calling loopy from read_object.
Hailwood
Yeah totally this would only work for one level of DOM. I had a read of recursion. Most people say that you dont really need to use it and can cause stack problems however it does save on code
Kieran