我从服务器获得以下JSON响应:
[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},
{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},
{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},
{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},
{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}]
如何制作jQuery foreach循环并仅获取id
和type
的值。
答案 0 :(得分:15)
var json = '[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}]';
$.each($.parseJSON(json), function() {
alert(this.id + " " + this.type);
});
答案 1 :(得分:9)
var json =
[
{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},
{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},
{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},
{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},
{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}
];
$.each(json,function(i,el)
{
alert(el.id+' - '+el.type);
});
Here是运行
的愚蠢示例修改强>
正如 enoyhs 所说,这也可以通过纯javascript实现,这将是一个更快的解决方案。 Here是javascript与jQuery中循环数组的基准:
答案 2 :(得分:2)
此处的工作示例:http://jsfiddle.net/ezmilhouse/emCT8/
创建仅包含id和type键的新对象数组的代码段:
var json = [{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}];
var arr = [];
$.each(json, function(key, value){
arr.push({
id: value.id,
type: value.type
});
});
console.log(arr);
答案 3 :(得分:0)
尝试:
<script type="text/javascript">
$(document).ready(function () {
var x = { "A" : {"A1": "1" } };
$.each(x, function(i,v) {
alert(i);
console.log(i);
});
});
</script>