Display all items in a json array

javascript, jquery, json

Solution

A nested loop (or, in jQuery, a nested `$.each()`) will do the job:

$.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=&client=104929', function(data){
   $.each(data, function(index, item){
      // create an empty ul (initially disconnected from the DOM)
      var $ul = $("<ul/>");

      // iterate over the line items
      $.each(item.invoice.line_items, function(i, lineItem) {
         // create an li element with the line details and append
         // it to the ul
         $ul.append( $("<li/>").html(lineItem.name_and_description + lineItem.price) );
      });

     // add the totals to the end of the ul
     $ul.append( $("<li/>").html(item.invoice.total_billed) );

     // create a new div, append the ul to it, and append the div to results
     $('#results').append( $('<div class="lineItem"/>').append($ul) );
   });
});

Problem

I am trying to work with json and I almost have what I need. I am getting the correct info to display but I am having to pass each item of an array into a variable and then print the variable. I would like to display all of the items in each array. The json data I am working with is from an invoicing app (www.curdbee.com) and I am trying to show each invoice for a client. The data that I want to show is each line item, the line item price, and the total amount. Here is my code: ``` $(document).ready(function() { $.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=__token__', function(data){ $.each(data, function(index, item){ var total = item.invoice.total_billed; var lineItemName1 = item.invoice.line_items[0].name_and_description; var lineItemName2 = item.invoice.line_items[1].name_and_description; var lineItemPrice1 = item.invoice.line_items[0].price; var lineItemPrice2 = item.invoice.line_items[1].price; $('#results').append('<div class="lineItem"><ul><li>' + lineItemName1 + lineItemPrice1 + '</li><li>' + lineItemName2 + lineItemPrice2 + '</li><li>' + total + '</li></ul></div>'); }); }); }); ```

Original source