-1

How can I call the loadlist function correctly when I have this JSON data?

I am calling like this but it’s not working:

loadlist($('select#selName').get(0), 'pull.php','data.name')

Here is my JSON data:

{
  data: [
    {
      id: "e0b0d8sc5ffd82e",
      name: "John",
    }
  ]
}

the function

function loadlist(selobj,url,nameattr) {
  $(selobj).empty();
  $.getJSON(url,{},function(data)
  {
    $(selobj).append(
        $('<option>Select</option>')
                    .val('null')
    );

    $.each(data, function(i,obj)
    {
        $(selobj).append(
             $('<option></option>')
                    .val(obj[nameattr])
                    .html(obj[nameattr]));
    });
  });
}
PaulWill
  • 613
  • 4
  • 18

1 Answers1

4

Your assumption that obj["data.name"] is equal to obj.data.name is wrong. (The equivalent requires two property accesses: obj["data"]["name"])

If you think you might need to do nested property retrievals, you might have better luck passing in a function for retrieving the property. (This also will work if you need to use a dynamically computed value.)

function loadlist(selobj,url,getter) {
  $(selobj).empty();
  $.getJSON(url,{},function(data)
  {
    $(selobj).append(
        $('<option>Select</option>')
                    .val('null')
    );

    $.each(data, function(i,obj)
    {
        var value = getter(obj);
        $(selobj).append(
             $('<option></option>')
                    .val(value)
                    .html(value));
    });
  });
}

// Call as follows:
loadlist($('select#selName').get(0), 'pull.php', function (obj) {
    return obj.data.name;
});
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134