Luke Bray
Luke Bray

Reputation: 245

How can I output a dynamic JSON array into a HTML table?

I have a function which is called on a button press and adds to an array order:

var order = [];

function updateCart(item) {
    var index = order.findIndex(i => i.id == item.id);
    if (index != -1) {
        order.splice(index, 1);
        order.push(item);
    } else {
        order.push(item);
    }
    $("#test").html(JSON.stringify(order));            
}

If the user adds 2 of one item and 1 of another item then order might look like this:

[{"id":1,"name":"Hawaiian","price":10,"qty":2},
 {"id":2,"name":"New Yorker","price":10,"qty":1}];

I would like to be able to loop through each item in the array and have a HTML table that can show each order in an easy to read way. For example:

<table>
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td>order[0].name</td>
            <td>order[0].qty</td>
        </tr>

        <tr>
            <td>order[1].name</td>
            <td>order[1].qty</td>
        </tr>
    </tbody>
</table>

If I pass the array to my table then it just seems to replace the entire table and not pass the values into where I have specified. See my below example:

<script>
$("#test").html(JSON.stringify(order));  
</script>

<table id="myTable">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
        </tr>
    </thead>

    <tbody>
        <script>
            for (var i = 0; i < order.length; i++) {
                document.write("<tr>");
                    document.write("<td>");
                        document.write(order[i].name);
                    document.write("</td>");
                document.write("</tr>");
            }
        </script>
        <tr>
            <td></td>
            <td></td>
        </tr>

        <tr>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

I am wondering if there is an easier way to do what I want. HTML DOM tables seem quite clunky. Thank you

Upvotes: 0

Views: 343

Answers (1)

mbojko
mbojko

Reputation: 14699

You can use map.

HTML:

<table>
  <thead>
    <tr>
      <th>Item</th>
      <th>Quantity</th>
  </thead>
  <tbody id="test">

  </tbody>
</table>

JS:

const order = [
  { id: 1, name: "Hawaiian", price: 10, qty: 2 },
  { id: 2, name: "New Yorker", price: 10, qty: 1 }
];

const singleRow = ({ name, qty }) => `<tr><td>${name}</td><td>${qty}</td></tr>`;
$("#test").html(order.map(singleRow).join(''));

https://codepen.io/anon/pen/MReZdL

Upvotes: 2

Related Questions