迭代对象数组 [英] Iterate over array of objects

查看:82
本文介绍了迭代对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的JSON字符串

I have a JSON string like this

 var json =  '{ "Comments": 
    [
      { "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},
      { "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}
    ] 
    }';

我试图迭代这些对象:

var parsedJSON = $.parseJSON(json);

var html = "";    
for (comment in parsedJSON.Comments) {
  html += "Id: " + comment.Id;
  html += "Comment: " + comment.Comment;
  html += "Name: " + comment.Name;
  html += "Child: " + comment.Child;
  html += "<br/>";
}

但这里评论 for for循环只变为 0 1 ,我的意思不是一个对象而只是一个字符串,我怎么能迭代这个数组?

But here comment in for loop becomes 0 and 1 only, I mean not an object but just a string, how can I iterate over this array?

推荐答案

var json = '{ "Comments": [{ "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},{ "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}] }';

var parsedJSON = $.parseJSON(json), // jsonData should json
    html = "",
    comments =parsedJSON.Comments; // keeping reference of parsedJSON and its an Array

// Here key will give 0, 1 etc ie. index of array

for (var key in comments) {
    html += "Id: " + comments[key].Id;
    html += "Comment: " + comments[key].Comment;
    html += "Name: " + comments[key].Name;
    html += "Child: " + comments[key].Child;
    html += "<br/>";
}

演示

Demo

这篇关于迭代对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆