Julian Sanchez
Julian Sanchez

Reputation: 101

How do I parse an object in an arrary in Javascript

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

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

I want searchitunes(params).then(console.log) to be a variable instead of being logged.

Upvotes: 1

Views: 49

Answers (2)

Michael Berry
Michael Berry

Reputation: 72254

Assuming that this follows the normal Javascript promises framework, then console.log is just a function passed into it like any other. So you can just use your own function where you access the response directly as a variable:

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

Or if you prefer the newer lambda syntax (the two are identical):

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

As per the comment, you can obtain the artwork URL by just traversing the object the same as you would any other object, so:

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

From there you can use AJAX to obtain the contents of that URL, or just create an img element that points to it.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138257

Just access it inside the then handler:

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

Or using async / await:

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

Upvotes: 1

Related Questions