nunof nunof - 2 years ago 73
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.

url : '' + encodeURIComponent(''),
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;

Here is the output from the console log:

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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download