jQuery $ .each()JSON数组对象迭代 [英] JQuery $.each() JSON array object iteration

查看:89
本文介绍了jQuery $ .each()JSON数组对象迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试解决JQuery $ .each()迭代时遇到一些真正的困难

I am having some real difficulty attempting to solve a JQuery $.each() iteration

这是我的数组,为方便起见,限制了结果

This is my array, limiting results for convenience

[{"GROUP_ID":"143",
  "GROUP_TYPE":"2011 Season",
  "EVENTS":[
    {"EVENT_ID":"374","SHORT_DESC":"Wake Forest"},
    {"EVENT_ID":"376","SHORT_DESC":"Yale"},
    {"EVENT_ID":"377","SHORT_DESC":"Michigan State"}]
 },
 {"GROUP_ID":"142",
  "GROUP_TYPE":"2010 Season",
  "EVENTS":[
    {"EVENT_ID":"370","SHORT_DESC":"Duke"},
    {"EVENT_ID":"371","SHORT_DESC":"Northwestern"},
    {"EVENT_ID":"372","SHORT_DESC":"Brown"}]
}]

我的第一个$.每次迭代都工作得很好,但是"EVENTS"的子迭代是我遇到问题的地方

My first $.each iteration works very well, but the sub iteration for "EVENTS" is where I am having issues

我的第一个$ .each()函数

My first $.each() function

     $.each(json, function(key) {

            html = '<a href="'+json[key].GROUP_ID+'">';

     ....

我无法使用的第二个$ .each()函数

My non-working second $.each() function

     $.each(json.EVENTS, function(key) {
    newHTML += '<p>'+json.EVENTS[key].SHORT_DESC+'</p>';


     ...

我在(松散地)理解这不是单个JSON对象,而是对象的JSON数组,但不了解第一个版本是否有效,为什么第二个版本不起作用

I am understanding (loosely) that this is not a singular JSON object, but a JSON array of objects, but not understanding if the first version works why the second does not

一旦我了解到这是$ .each()中的$ .each(),我想要实现的最终结果,我知道下面的代码不起作用,而且很可能是白痴,但可以给出一个想法我正在尝试实现:先通过父项然后逐个父项进行迭代

the end result I want to achieve once I understand this is an $.each() within an $.each(), I know the code below does not work, and more than likely idiotic, but gives an idea of what im trying to achieve : iterate through parent then child by parent

$.each(json, function(key) {

            html = '<a href="'+json[key].GROUP_ID+'">';

     $.each(json[key].EVENTS, function(subkey) {

            html = '<a href="'+json[key]EVENTS[subkey].SHORT_DESC+'">';
 ...

推荐答案

还要为$.each function()分配第二个变量,这将为您提供数据更加容易(因此您不必工作)带有索引).

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

应该打印出您在问题中尝试的所有内容.

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

编辑重命名了变量,以使其更容易理解什么是什么.

edit renamed the variables to make it bit easier to understand what is what.

这篇关于jQuery $ .each()JSON数组对象迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆