John Taylor
John Taylor

Reputation: 55

How do I add an array of objects into an HTML Table?

I am gathering JSON string data on a button click. Each time I click the button another product gets added to the array. The array is an array of objects:

{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}

How would I take this information and insert it into a table? say I have

<div id='table'>
    <table>
    </table>
</div>

JavaScript:

var prodArr=[{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", 
product_name: "Tennis balls"}];

function buildTable(data){
    var table = document.getElementById('table');
    const arr = data;
    for(var obj of arr){
        var row = document.createElement('tr');
        for(var val of Object.values(obj)){
            var col = document.createElement('td');
            col.textContent = val;
            row.appendChild(col);
        }
        table.appendChild(row);
    }
}

buildTable(prodArr);

I would like to add headers for SKU:, retail_price:, list_price: product_name: and a textbox for quantity on each row as well.

Upvotes: 1

Views: 2439

Answers (1)

Unmitigated
Unmitigated

Reputation: 89204

You can loop over the array, use Object.values to loop over the values of the object, and use document.createElement to create new table rows to add to the table.

const table = document.getElementById('table');
const arr = [{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}];
for(const obj of arr){
  const row = document.createElement('tr');
  for(const val of Object.values(obj)){
    const col = document.createElement('td');
    col.textContent = val;
    row.appendChild(col);
  }
  table.appendChild(row);
}
table, tr, td, th {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 2px;
}
<table id="table">
</table>

Upvotes: 1

Related Questions