Ad

How To Loop A Nested Array Object In Javascript With Jquery

Hey im working on a project and i can't seem to get the hang of this. I want to loop through my nested array object "products" so that i can display it all and not just the last index.

// jquery getting our json order data from firebase
    $.get("http://localhost:8888/orderslist", (data) => {    


        // i is for the index of the array of orders
        let i = 0;    
        //for each loop through our array list
        $.each(data, function () {
            //console.log(data)
            //console.log(i);
            // is how we arrange the data and show it to the frontpage
            $(`<table id = order_table_layout>
                    <tr>
                        <th>Customer</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>Total</th>
                        <th>Order</th>
                        <th>Order Status</th>
                    </tr>
                    <tr>
                        <td>${data[i].customer_name}</td>
                        <td>${data[i].date}</td>
                        <td>${data[i].time}</td>
                        <td>${data[i].total} Kr.</td>

                        <td>
                            ${data[i].products[i].name}
                            ${data[i].products[i].price} Kr.
                        </td>

                        <td>

                        </td>
                    </tr>
                </table>`

            ).appendTo("#frontpage_new_ordertable");        
            // counts 1 up for each loop to go through list
            i++;
            //console.log(i);
        });
    });

Edit: An example of the json data I'm working with look like this:

[
  {
    id: "4WQITi6aXvQJsKilBMns",
    customer_name: "Susanne",
    date: "22-12-2002",
    time: "12:43:19",
    total: 222,
    products: [
      { name: "product name",  price: 100 },
      { name: "product name2", price: 20  }
    ]
Ad

Answer

There's a couple of issues in your code. Firstly you're creating a brand new table for every object in the data array. It makes far more sense to instead create a new row in the table for each item.

Also, it appears that you want to loop through the child products array. As such you need an inner loop to create the HTML string for those elements outside of the template literal.

However it's worth noting that it's not good practice to have that much HTML in your JS. A better approach is to have a hidden template tr in your HTML which you can clone, update with the data from the data array, then append to the DOM in the tbody of the table.

With that said, try this:

//$.get("http://localhost:8888/orderslist", (data) => {
  // mock response:
  let data = [{id:"4WQITi6aXvQJsKilBMns",customer_name:"Susanne",date:"22-12-2002",time:"12:43:19",total:222,products:[{name:"product name",price:100},{name:"product name2",price:20}]},{id:"asjdkjk21ijjjew",customer_name:"Foo Bar",date:"10-05-2020",time:"16:46:16",total:68,products:[{name:"Lorem ipsum",price:50},{name:"Fizz buzz",price:18}]}];

  let rows = data.map(item => {
    let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
    $clone.find('.customer-name').text(item.customer_name);
    $clone.find('.date').text(item.date);
    $clone.find('.time').text(item.time);
    $clone.find('.total').text(item.total + ' Kr.');

    let products = item.products.map(prod => `${prod.name}: ${prod.price} Kr.`);
    $clone.find('.products').html(products.join('<br />'));
    return $clone;
  });

  $("#frontpage_new_ordertable tbody").append(rows);
//});
tfoot { 
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="frontpage_new_ordertable">
  <tbody>
    <tr>
      <th>Customer</th>
      <th>Date</th>
      <th>Time</th>
      <th>Total</th>
      <th>Order</th>
      <th>Order Status</th>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class="customer-name"></td>
      <td class="date"></td>
      <td class="time"></td>
      <td class="total"></td>
      <td class="products"></td>
      <td></td>
    </tr>
  </tfoot>
</table>

Ad
source: stackoverflow.com
Ad