How to use nested foreach loop in jQuery?

Viewed 391

My array looks like this

 productTable:Array(3)
  '[{
      id:1
      name:"Apple"
      today:10
      yearly:21
    },
  {
      id:2
      name:"Banana"
      today:14
      yearly:45
   },
   {
      id:2
      name:"Mangoes"
      today:5
      yearly:95
   },

I want to make table like this

Period | Apple  | Banana  | Mangoes |
-------+--------+---------+---------+
Yearly |   21   |   45    |   95    |
Today  |   10   |   14    |    5    |

and my html code is where id=product title is for Product title & id=product_item is for data like above.

         <table>
            <tr id="product_title">
            </tr>
             <tbody>
            <tr id="product_item">
             </tr>
            </tbody>
        </table>

My script file is this; I am getting an error from this. All data are getting undefined.

<script>
    fetch('http://127.0.0.1:8000/api/productTable')
     .then(response=>response.json())
     .then(data=>{
       $('#product_title').append("<th>Period</th>");
            data.productTable.forEach(function (product) {
            $('#product_title').append('<th>'+product.name +'</th>');
       });
    $.each(['yearly','today'],function (i,period) {
         $('#product_item').append('<td>'+ period +'</td>');
          $.each(data.retailsTable, function(result) {
           $('#product_item').append('<td>'+ result.period +'</td>');
        });
    })
});
</script>
1 Answers

First you need the separate rows for your periods which you can create with a simple loop and give each row an id from the period value. These rows could also be hard coded into the html if you prefer

Then move the existing period loop inside the loop of the main array so you add the name to heading row and each associated period value to the period rows

For variable property names use [] notation

['Yearly', 'Today'].forEach(period => {
  const id = period.toLowerCase();
  const $row = $('<tr>', {id: id}).append($('<th>', {text: period}));
  $('#product_table').append($row)
})

$('#product_title').append("<th>Period</th>");

// loop over each item in array
data.forEach(product => {
  // insert name in heading row
  $('#product_title').append('<th>' + product.name + '</th>');
  // inner loop for each product period value
  ['yearly', 'today'].forEach(period => {
    const $row = $('#' + period);
    $row.append('<td>' + product[period] + '</td>')
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="product_table">
  <tr id="product_title">
  </tr>
  <tbody>
    <tr id="product_item">
    </tr>
  </tbody>
</table>

<script>
  const data = [{
      id: 1,
      name: "Apple",
      today: 10,
      yearly: 21
    },
    {
      id: 2,
      name: "Banana",
      today: 14,
      yearly: 45
    },
    {
      id: 2,
      name: "Mangoes",
      today: 5,
      yearly: 95
    }
  ]
</script>

Related