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
How to iterate json data in jquery
提问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
回答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);
});