[英]Accessing second array in a JSON decode using Jquery
I need to access the second array from a JSON decoded
string, but I am having no luck. 我需要从JSON decoded
字符串访问第二个数组,但是我没有运气。
The entire JSON string is displayed in var RAW00
, and then split into var RAW01
& var RAW02
. 整个JSON字符串显示在var RAW00
,然后拆分为var RAW01
和var RAW02
。 All 3 of these are for testing - RAW00 is identical to msg
所有这三个都在测试中RAW00 is identical to msg
When they are split - I can access either, depending on what variable I start of with, but when I use RAW00
I cannot access the tutor section. 当它们被拆RAW00
-我可以访问任何一个,这取决于我以哪个变量开头,但是当我使用RAW00
我无法访问“教师”部分。
I will provide more detail if required, but my question is: 如果需要,我将提供更多详细信息,但我的问题是:
How do I see and access the tutor array in the second $.each
(nested) block?? 我如何在第二个$.each
(嵌套)块中查看和访问导师数组? ] ]
Thanks :-) 谢谢 :-)
success: function(msg)
{
var test = "";
var raw00 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
},
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
var raw01 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
}
]
};
var raw02 = {
"allData": [
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
$.each(raw00.allData, function(index, entry)
{
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.name+'</td></tr>';
});
$('#all-courses-table-content').html( test );
});
You need to check whether the current element of the array is an object with class2
property or tutor
property. 您需要检查数组的当前元素是具有class2
属性还是tutor
属性的对象。
$.each(raw00.allData, function(index, entry) {
if (entry.hasOwnProperty('class2')) {
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
}
if (entry.hasOwnProperty('tutor')) {
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.fname+'</td></tr>';
});
}
$('#all-courses-table-content').html( test );
});
Things would probably be simpler if you redesigned the data structure. 如果重新设计数据结构,事情可能会更简单。 It generally doesn't make sense to have an array of objects when each object just has a single key and it's different for each. 当每个对象只有一个键并且每个键都不相同时,通常没有数组对象是没有意义的。 I suggest you replace the allData
array with a single object, like this: 我建议您用单个对象替换allData
数组,如下所示:
var raw00 = {
"allData": {
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
],
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.