Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  118] [ 4]  / answers: 1 / hits: 45295  / 11 Years ago, sun, january 12, 2014, 12:00:00

I have the JSON object returned by the api of last.fm as follow:



{
artists: {
artist: {
name: Daft Punk,
playcount: 494599,
listeners: 106101,
mbid: 056e4f3e-d505-4dad-8ec1-d04f521cbb56,
url: http://www.last.fm/music/Daft+Punk,
streamable: 1,
image: [
{
#text: http://userserve-ak.last.fm/serve/34/5463.jpg,
size: small
},
{
#text: http://userserve-ak.last.fm/serve/64/5463.jpg,
size: medium
},
{
#text: http://userserve-ak.last.fm/serve/126/5463.jpg,
size: large
},
{
#text: http://userserve-ak.last.fm/serve/252/5463.jpg,
size: extralarge
},
{
#text: http://userserve-ak.last.fm/serve/500/5463/Daft+Punk.jpg,
size: mega
}
]
},
@attr: {
page: 1,
perPage: 1,
totalPages: 1000,
total: 1000
}
}
}


Now I am trying to get the images from the object but the key for the image url is #text. I have no idea how is this value extracted in Javascript. I am using AngularJS but any suggestions using plain javascript also is okei. Is there any way I can use # in the key of the object to get its value.



Any help would be greatly appreciated.



Cheers :)


More From » json

 Answers
227

Assuming it's in the obj var, this would return an array with the images



var imgSrcArray = obj.artists.artist.image.map(function(image){ return image['#text'] });


ES6:



const imgSrcArray = obj.artists.artist.image.map( image => image['#text'] );


That's it.



if you want to classicaly traverse this array, with this:



var images = obj.artists.artist.image;
for(var i=0; i < images.length; i++){
var image = images[i];
var url = image['#text'];
console.log(url: , url); //Outputs the img url
}


Cheers


[#73221] Saturday, January 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;