如何在Javascript中解析arrary中的对象

时间:2018-05-02 15:17:50

标签: javascript arrays json api parsing

const params = {
    entity: 'musicTrack',
    term: 'Muzzy New Age',
    limit: 1
};

searchitunes(params).then(console.log);

我希望searchitunes(params).then(console.log)成为变量而不是记录。

2 个答案:

答案 0 :(得分:1)

假设这遵循正常的Javascript promises framework,那么console.log就像传递给它的函数一样。因此,您可以使用自己的函数直接作为变量访问响应:

searchitunes(params).then(function(response) {
    //Your result is now in the response variable.
});

或者如果您更喜欢较新的lambda语法(两者相同):

searchitunes(params).then(response => {
  //Your result is now in the response variable.
});

根据评论,您可以通过遍历对象来获取图片URL,就像使用任何其他对象一样,所以:

var artworkurl = response.results[0].artworkUrl100;

您可以use AJAX从那里获取该网址的内容,或只是create an img element that points to it

答案 1 :(得分:1)

只需在then处理程序中访问它:

 searchitunes(params).then(result => {
   // Use result here
 });

或使用async / await:

 (async function() {
   const result = await searchitunes(params);
   // Use result here
 })();