jQuery 如何在jquery中迭代json数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4233354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:54:23  来源:igfitidea点击:

How to iterate json data in jquery

jqueryjson

提问by Elankeeran

How to iterate the json data in jquery.

如何在jquery中迭代json数据。

[{"id":"856","name":"India"},
 {"id":"1035","name":"Chennai"},
 {"id":"1048","name":"Delhi"},
 {"id":"1113","name":"Lucknow"},
 {"id":"1114","name":"Bangalore"},
 {"id":"1115","name":"Ahmedabad"},
 {"id":"1116","name":"Cochin"},
 {"id":"1117","name":"London"},
 {"id":"1118","name":"New York"},
 {"id":"1119","name":"California"}
]

回答by Nick Craver

You can use $.each()like this:

你可以这样使用$.each()

$.each(data, function(i, obj) {
  //use obj.id and obj.name here, for example:
  alert(obj.name);
});

回答by cambraca

You can just use regular javascript too, which I think would be a bit faster (though I'm not really sure how jQuery optimizes each):

你也可以使用普通的 javascript,我认为这会快一点(虽然我不太确定 jQuery 是如何优化的each):

var data = [{"id":"856","name":"India"},
 {"id":"1035","name":"Chennai"},
 {"id":"1048","name":"Delhi"},
 {"id":"1113","name":"Lucknow"},
 {"id":"1114","name":"Bangalore"},
 {"id":"1115","name":"Ahmedabad"},
 {"id":"1116","name":"Cochin"},
 {"id":"1117","name":"London"},
 {"id":"1118","name":"New York"},
 {"id":"1119","name":"California"}
];

var data_length = data.length;
for (var i = 0; i < data_length; i++) {
  alert(data[i]["id"] + " " + data[i]["name"]);
}

editedto reflect Nick's suggestion about performance

编辑以反映尼克对性能的建议

回答by shayuna

iterate on all the object's properties with the $.each function. in each iteration you'll get the name/key and the value of the property:

使用 $.each 函数迭代对象的所有属性。在每次迭代中,您将获得属性的名称/键和值:

$.each(data, function(key, val) {
  alert(key+ " *** " + val);
});

回答by Darin Dimitrov

You could use the .each()function:

您可以使用该.each()功能:

$(yourjsondata).each(function(index, element) {
    alert('id: ' + element.id + ', name: ' + element.name);
});