用for循环遍历多个测试的json对象



我一直试图通过一个多嵌套json对象循环,但每次它显示未定义。我想显示播放数和歌名。我打算用条形图来表达。

I tried this expecting ['playcount', 'name']
function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let testarray = result[0]['album'];
let newdata = [];
for (let i = 0; i < result.length; i++) {
testarray= result[i]['album']
console.log(testarray)
let item = []
item[0] = testarray[i]['playcount']
item[1] = testarray[i]['name']
newdata[j] = item

console.log(newdata);
}
console.log(newdata)
})

}

让我们首先看一下您正在处理的数据:

result = {
"topalbums":
{
"album": 
[
{
"name": "So Far Gone",
"playcount": 12543719,
"mbid": "f05567cc-6ed3-40e0-bad1-7812478eecbe",
"url": "https://www.last.fm/music/Drake/So+Far+Gone",
"artist": { ... }
"image": [ ... ]
},
...
],
"@attr": { ... }
}
}

你正在获取一个对象,它有一个属性,键名为topalbums。热门专辑有两个属性;数组album和一个名为@attr的对象.
从它的外观来看,您希望访问相册中的对象。nameplaycount.

考虑到你正在处理的数据,我假设这就是你要寻找的:

let newdata =
[
{
"playcount": 123123
"name": "album name1"
},
{
"playcount": 12456543
"name": "album name2"
},
...
]
为了达到这个目的,你可以按照以下方式修改代码:
function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let albumArray = result["topalbums"]["album"]; // This gets you the album array
let newdata = [];
for (let i = 0; i < albumArray.length; i++) {
const albumSummary = {} // Create a new object
albumSummary["name"] = albumArray.name // Add name to the object
albumSummary["playcount"] = albumArray.playcount // Add playcount to the object
newdata.push(albumSummary) // Add the object to the array
}
console.log(newdata)
})
}

或者,如果你不想要一个对象的数组,而是像[['playcount', 'name']...]这样的数组的数组,你可以像这样修改上面的代码:

function getData(){
$("#output").html("<b>hi there</b>");
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=drake&api_key=22102f7d3a814de0736edf670bd2c771&format=json',function(result){
console.log(result);
let albumArray = result["topalbums"]["album"]; // This gets you the album array
let newdata = [];
for (let i = 0; i < albumArray.length; i++) {
const albumSummary = [] // Create a new array
albumSummary.push(albumArray.name) // Add name to the array
albumSummary.push(albumArray.playcount) // Add playcount to the array
newdata.push(albumSummary) // Add the array to the array
}
console.log(newdata)
})
}

希望这对你有帮助!

最新更新