nunof nunof - 6 months ago 10
JSON Question

How can I access the value from an Object inside an array

When i loop from a rss data I want to extract the url value from an object.

$.ajax({
url : 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=30&callback=?&q=' + encodeURIComponent('http://www.dnoticias.pt/rss/actualidade/geral'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {

title = e.title;
description = e.description;
category = e.categories[0];
media = e.mediaGroups;
console.log(media);
}
}
});


Here is the output from the console log:

mediaGroups: Array[1]
0: Object
contents: Array[1]
0: Object
type: "image/jpeg"
url: "http://...."


Thanks

Answer

From the output you've shown mediaGroups is an array of objects, which themselves contain a contents property which is another array of objects, so you need to use nested loops to pull out each url property from those objects.

$.each(data.responseData.feed.entries, function(_, entry) {
    $.each(entry.mediaGroups, function(_, mediaGroup) {
        $.each(mediaGroup.contents, function(_, content) {
            var url = content.url;
            // use url as required here...
        });
    });
});

If you always only ever want to retrieve the first item from the array, and can guarantee that each child array will contain at least one item, then you can simply access them by index like this:

$.each(data.responseData.feed.entries, function (i, entry) {
    var url = entry.mediaGroups[0].contents[0].url;
    // use url as required here...
});

Working example

Comments