-1

I have the following table which I will like to set the rows with some values from an api when the page loads. I have some static values for now and the api returns a JSON array.

<table class="table table-striped table-valign-middle">
    <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Sales</th>
            <th>More</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <img src="default-150x150.png" alt="Product 1" class="img-circle img-size-32 mr-2" />
                product 1
            </td>
            <td>$ 200</td>
            <td>
                <small class="text-success mr-1">
                    <i class="fas fa-arrow-up"></i>
                    0.5%
                </small>
                2 Sold
            </td>
            <td>
                <a href="#" class="text-muted">
                    <i class="fas fa-search"></i>
                </a>
            </td>
        </tr>
    </tbody>
</table>

I have the following information in the JSON array as an example and product , price, sales maps to Name, price and count respectively. would like to do that via JavaScript or jquery.

+-----------+-------------+-------+------+-------+
|        ID | Name        | Price | URL  | Count |
+-----------+-------------+-------+------+-------+
|         1 | Book        | 2     | url1 |     2 |
|         2 | Pen         | 1     | url2 |     1 |
|         3 | pencil      | 1     | url3 |     1 |
+-----------+-------------+-------+------+-------+
Robert
  • 29
  • 6
  • 2
    what is in the array, where is the javascript code you made to try and achieve your goal? SO expects the OP to make an attempt – Ramon de Vries Oct 05 '20 at 11:46
  • sorry i mistakenly deleted some part of the question. I just edited – Robert Oct 05 '20 at 11:52
  • Duplicate: https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table and https://stackoverflow.com/questions/29335369/display-array-of-objects-in-a-dynamic-table-javascript make an attempt then ask for help if you get stuck. And what you have shown is NOT JSON array format. – ikiK Oct 05 '20 at 12:22

1 Answers1

3

First Clear table body using .empty()

$('tbody').empty();

Create on variable to store table body html.

var html = '';

Loop through each row in JSON array and append row in html.

$.each(product, function (i, item) {
    html += '<tr>';
    html += '<td>' + item.ID + '</td>';
    html += '<td>' + item.Name + '</td>';
    html += '<td>' + item.Price + '</td>';
    html += '<td>' + item.URL + '</td>';
    html += '<td>' + item.Count + '</td>';
    html += '</tr>';
});
$('tbody').append(html);