递归循环javascript对象?
我正在尝试创建一个函数,
当给定一个对象时,该函数将输出类似“
<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
}
}
}
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
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将方法与主调用分开。
Separate the method out from the main call.