[英]How do I iterate over a nested JSON during Ajax?
我有這個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",
"": ""
},
...
]
}
我想返回所有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 />");
}
}
});
}
但是我從控制台看到此錯誤
未捕獲的TypeError:無法讀取未定義的屬性“ id”
我也嘗試了這個for
循環(控制台出現語法錯誤)
for(var i = 0; i < samples.data.length; i++)
{
var product = samples.data[i];
var productId = product.id;
console.log(productId);
}
我想要的只是輸出5, 8
(我的id
)
我對JSON不太熟悉,那么如何正確訪問和遍歷我的結構?
您可以嘗試使用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
需要是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.