Evonet
Evonet

Reputation: 3640

Getting undefined when iterating from JSON API results

I'm having problems reading my JSON result from an API.

My data looks like this:

{
    "Data": [
        {
            "Name": "Company1"
        },
        {
            "Name": "Company2"
        }
    ]
}

And I'm reading it like this:

$.get(API_URL + '/dashboard/', function (data) {
    var newHTML = '';

    $.each(data, function (i, val) {
        newHTML +=  data[i].Name;
    });

    $('#dashboard').html(newHTML);

});

data[i] is returning undefined. What am I doing wrong?

Upvotes: 1

Views: 48

Answers (1)

Mr.Web
Mr.Web

Reputation: 7154

This should work for you.

$.get(API_URL + '/dashboard/', function (data) {
    var newHTML = '';

    $.each(data.Data, function (i, val) {
        newHTML +=  val.Name;
    });

    $('#dashboard').html(newHTML);

});

The each function need to parse the data.Data, not just data...

Sounds like a pun! But should work!

Upvotes: 2

Related Questions