2012-02-29 99 views
0

我想使用jquery获取主题数组内的数据内容。如何才能做到这一点 ?我尝试使用$.each,但无法获取内容。如何遍历嵌套在对象中的数组?

"student": { 
    "name": "sdfdsf", 
    "age": 3, 
    "subject": [ 
     { 
      "science": "dfsdfdfd", 
      "book": "sdfds" 
     }, 
     { 
      "math": "vbcb", 
      "book": "sdfds" 
     } 
    ] 
} 

回答

0

在磁盘阵列上使用$。每个:

$.each(student.subject, function (arrayIndex, arrayItem){ 
    console.log(arrayItem.science); 
}); 
+1

但这真的不应该这样做。它比简单的for循环慢得多。 – maxedison 2012-02-29 02:30:26

+0

@maxedison只是看着一个性能测试,老实说,并没有意识到它是多少慢......好眼眸 – charlietfl 2012-02-29 02:43:33

2

不知道你遇到了什么问题,但下面将循环在阵列上的问题:

for(var i = 0; i < student.subject.length; i++){ 
    //student.subject[i] refers to the current item in the array 
} 

您一般会使用$.each()遍历一个对象的属性。在这种情况下,您只需循环一个数组。

+0

谢谢你最大.. – user1184100 2012-02-29 02:46:24

1

鉴于JSON(让我们称之为这里的信息)是节点的姓名,年龄,受的对象。 Subject是包含名称和书籍键值对的JSON数组。

在这里,您需要首先访问主题节点,这是一个数组,并迭代数组以获取每个子节点。可以在每个数组元素处再次访问键值对。

以下是迭代内容的源代码。

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
<style> 
</style> 
<script type="text/javascript"> 
$(document).ready(function() { 
var info={"student": { 
    "name": "Tom", 
    "age": 3, 
    "subject": [ 
     { 
      "science": "scscsc", 
      "book": "SciBook" 
     }, 
     { 
      "maths": "mmmm", 
      "book": "MathBook" 
     }, 
     { 
      "History": "hshshs", 
      "book": "hisBook" 
     } 
] 
}}; 
    var subjects=info["student"]["subject"]; 
    //Iterate all the subejcts present in the subject Node 

    for(i=0;i<subjects.length;i++){ 
    // Get the information of particular subejct 
     $.each(subjects[i],function(key,val){ 
      alert(i+"> Sub[ "+key+" ]="+val); 
     }) 
    } 
}); 
</script> 
</head> 
<body> 
</body> 
</html> 
+0

欢迎!如果它是你想要的,你可以接受答案:) – 2012-02-29 02:48:34