递归循环javascript对象?

时间:2010-09-29 06:46:45

标签: jquery json recursion object

我正在尝试创建一个函数,

给定对象时会输出类似

的内容
<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>

我该怎么做?

这是我的尝试:

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;
}

这是我正在使用的对象

{
  "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
    }
  }
}

1 个答案:

答案 0 :(得分:-1)

将方法与主要呼叫分开。


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
        }
    }
}