我有这个JSON,我不知道如何访问productList中的元素。这是JSON
[
{
"id": 1,
"name": "sala1",
"deleted": "NODELETED",
"sectionList": [
{
"id": 1,
"name": "seccion1",
"methodList": [],
"frecuencyList": [],
"productList": [
{
"id": 1,
"name": "lejia",
"deleted": "NODELETED"
},
{
"id": 3,
"name": "agua",
"deleted": "NODELETED"
},
{
"id": 4,
"name": "cal",
"deleted": "NODELETED"
}
],
"deleted": "NODELETED"
},
{
"id": 2,
"name": "seccion2",
"methodList": [],
"frecuencyList": [],
"productList": [
{
"id": 1,
"name": "lejia",
"deleted": "NODELETED"
}
],
"deleted": "NODELETED"
}
]
}
我正在使用它:
$.getJSON('my url' , function(data) {
$.each(data , function(key, val)
{
console.log("Value of ProductList-> " + data['productList'].name );
});
});
我是第一次将JSON与其他数组一起使用而且我输了。谢谢大家!!!
答案 0 :(得分:2)
data[0].sectionList[0].productList
会在其sectionList
集合的productlist
中为您的第一个项目提供第一项。
$.getJSON('my url' , function(data) {
$.each(data , function(key, val)
{
console.log("Value of ProductList-> " + val.sectionList[0].productList.name );
});
});
要获得每个产品列表,您需要另一个内循环。
$.getJSON('my url' , function(data) {
$.each(data , function(key, val)
{
$.each(val.sectionList , function(k, v){
console.log(v.productList.name);
}
});
});
答案 1 :(得分:0)
如果你想避免使用jQuery循环,你只需使用vanilla JS:
即可var productList = data[0].sectionList[0].productList;
for (var i = 0, l = productList.length; i < l; i++) {
console.log('Value of ProductList-> ' + productList[i].name);
}
答案 2 :(得分:0)
你也可以试试这个:
jQuery.each(data , function(key, val)
{
jQuery.each(val['sectionList'] , function(sectionIndex, section){
jQuery.each(section['productList'] , function(index, product){
alert("Value of ProductList-> " + product.name );
});
});
});