webworm
webworm

Reputation: 11019

jQuery each loop with single object returns "undefined"

I have a jQuery function that makes a call to an ASP.NET Web API. I know the API returns a client object successfully because I can enter the API url directly and the object info is displayed in XML format in the browser. The JSON data is returned as a collection and jQuery loops through and appends <option> elements to a <select> element.

What I am having trouble with is how to use jQuery to display the results. The jQuery works fine to display a collection of objects, however if only one object is returned it displays "undefined" for the <option> element.

   function searchClients() {
      var uri = 'api/clients';
      var searchParam = $('#SearchTerm').val();
      $.getJSON(uri + '/' + searchParam)
        .done(function (data) {
          $('#selSearchResults').show(); // Displays hidden select element
          $('#selSearchResults').html(""); // Clear any pre-existing data in select element
          $.each(data, function (key, item) {
            $('#selSearchResults')
              .append('<option value="' + key + '">' + item.OrgName + ' - ' + item.ID + '</option>');
          })
        })
        .fail(function (jqXHR, textStatus, err) {
            $('#ErrorMessage').text('Error: ' + err);
        });
    }

If the .each function receives a single object for data will if return undefined? If this is so how does one account for a result that may contain a single object or just one? I thought the .each would account for this.

Upvotes: 2

Views: 3055

Answers (2)

webworm
webworm

Reputation: 11019

Solved! The problem was that a single object was being returned and when this occurs the each() function iterates through the properties of the object. The solution was to "wrap" the single object into an array so each() would be able to iterate properly. I added this line to my jQuery ...

if (!jQuery.isArray(data)) data = [data]; // If a single object is returned, wrap it in an array

Here it is in the whole function.

function searchClients() {
   var uri = 'api/clients';
   var searchParam = $('#SearchTerm').val();
   $.getJSON(uri + '/' + searchParam)
     .done(function (data) {
       $('#selSearchResults').show(); // Displays hidden select element
       $('#selSearchResults').html(""); // Clear any pre-existing data in select element
       if (!jQuery.isArray(data)) data = [data]; // If a single object is returned, wrap it in an array
       $.each(data, function (key, item) {
         $('#selSearchResults')
           .append('<option value="' + key + '">' + item.OrgName + ' - ' + item.ID + '</option>');
       })
     })
     .fail(function (jqXHR, textStatus, err) {
         $('#ErrorMessage').text('Error: ' + err);
     });
}

I found the solution to this problem from the following SO article - JSON result containing only one item and looking at the answer from @CMS.

Upvotes: 1

Custodio
Custodio

Reputation: 8934

I strongly believe something wrong is coming from your API. Check if you actually sending an array, or objects for example.

Assure that your data looks like: var data = [ {ID: 01, OrgName: "Organization1"}, {ID: 02, OrgName: "Organization2"}, {ID: 03, OrgName: "Organization3"} ];

You can play with the data here: http://jsfiddle.net/lcustodio/FBdSj/

Upvotes: 0

Related Questions