[英]iterate through multinested json object with for loop
我一直在尝试遍历一个多嵌套的 json object 但每次它都显示未定义。 我想显示播放次数和歌曲名称。 我计划将其与条形图一起使用。
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": { ... }
}
}
您将获得一个 object,它有一个带有名为topalbums的键的属性。 热门专辑有两个属性; 一个名为album的数组和一个名为 @attr 的object 。
从它的外观来看,您想要访问专辑数组中的对象,更具体地说是name和playcount 。
鉴于您正在使用的数据,我认为这就是您要寻找的数据:
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']...]
的 arrays 数组,您可以像这样更改上面的代码:
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)
})
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.