JQuery 遍历字典数组

JQuery iterate over array of dictionaries

本文关键字:数组 字典 遍历 JQuery      更新时间:2023-09-26

我有一个由服务器在ajax请求中返回的dicts数组,如下所示:

var obj =  [{'id': '111', 'name': 'test1'}, {'id': '1975', 'name': 'test2'}]

当我尝试访问每个字典时:

$.each(obj,function(index,value){ 
    alert(index + " : " + value);
});

我收到错误:

未捕获的类型错误:无法使用"in"运算符在 [{'id': '111', 'name': 'test1'}, {'id': '1975', 'name': 'test2'}] 中搜索 '193'

如何访问数组中的每个字典?

你需要一个$.each()用于数组,另一个用于处理字典的元素(顺便说一句,大多数JS程序员称之为"对象")

$.each(obj,function(index,value){ 
    $.each(value, function(index2, value2) {
                alert(index2 + " : " + value2);
    }); 
});

我认为您编写的代码没有任何错误,这是完全正确的。

http://jsfiddle.net/neilmalgaonkar/3y79vr4s/

var obj=  [{'id': '111', 'name': 'test1'}, {'id': '1975', 'name': 'test2'}];
$.each(obj,function(index,value){ 
   console.log(index,  value);
});

只需从数组中删除 u 它应该可以工作

jQuery $.each函数只是javascripts for-in循环的包装器。您尝试迭代的对象无效。

循环正在查找基于该键的keyvalue。 但值u'111'是无效的 JS 对象表示法。

编辑:您说您删除了"u",但错误消息仍然说您拥有它...

var obj=  [{'id': '111', 'name': 'test1'}, {'id': '1975', 'name': 'test2'}]
$(obj).each(function(index,value){ 
    alert("index: " + index + ",  id: " + value.id + ",  name: " + value.name);
});

工作 : http://jsfiddle.net/wvqkfb1f/