[英]How do I iterate over a nested JSON during Ajax?
I have this JSON: 我有这个JSON:
{
"draw": 0,
"recordsTotal": 90,
"recordsFiltered": 41,
"data": [
{
"id": "5",
"art": "default/def2.jpg",
"full_name": " ",
"title": "Hellberg - The Girl | Atomik Remix",
"tag": "music",
"time": "2015-11-14",
"": ""
},
{
"id": "8",
"art": "default/def2.jpg",
"full_name": "Simon Deoro",
"title": "Tim McMorris-On (Single)",
"tag": "dance,popular,",
"time": "2015-11-14",
"": ""
},
...
]
}
I want to return all id
's inside data
, so I tried this function: 我想返回所有
id
的内部data
,所以我尝试了以下功能:
function getPlaylist(id) {
$.ajax({
type: "GET",
url: baseUrl+"/playlist.php?id="+id,
cache: false,
success: function(result) {
var samples = JSON.parse( result );
for (i in samples)
{
console.log(samples.data[i].id + "<br />");
}
}
});
}
however I see this error from console 但是我从控制台看到此错误
Uncaught TypeError: Cannot read property 'id' of undefined
未捕获的TypeError:无法读取未定义的属性“ id”
I tried also this for
loop (syntax error from console) 我也尝试了这个
for
循环(控制台出现语法错误)
for(var i = 0; i < samples.data.length; i++)
{
var product = samples.data[i];
var productId = product.id;
console.log(productId);
}
All I want is output 5, 8
(my id
's) 我想要的只是输出
5, 8
(我的id
)
I'm not very familiar with JSON, so how can I access and iterate over my structure correctly? 我对JSON不太熟悉,那么如何正确访问和遍历我的结构?
You can try using the map
function to transform the array to another array. 您可以尝试使用
map
函数将数组转换为另一个数组。
var dataJSON = { "draw": 0, "recordsTotal": 90, "recordsFiltered": 41, "data": [ { "id": "5", "art": "default/def2.jpg", "full_name": " ", "title": "Hellberg - The Girl | Atomik Remix", "tag": "music", "time": "2015-11-14", "": "" }, { "id": "8", "art": "default/def2.jpg", "full_name": "Simon Deoro", "title": "Tim McMorris-On (Single)", "tag": "dance,popular,", "time": "2015-11-14", "": "" }, ] }; var obj = dataJSON.data.map((currentValue) => currentValue.id); console.log(obj);
function getPlaylist(id) { $.ajax({ type: "GET", url: baseUrl+"/playlist.php?id="+id, cache: false, success: function(result) { var samples = JSON.parse( result ); var idArray = samples.data.map(x => x.id); console.log(idArray); } });
samples
needs to be samples.data
. samples
需要是samples.data
。
function getPlaylist(id) {
$.ajax({
type: "GET",
url: baseUrl+"/playlist.php?id="+id,
cache: false,
success: function(result) {
var samples = JSON.parse( result );
for (i in samples.data)
{
console.log(samples.data[i].id + "<br />");
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.