Hello i would like my array to create a table for me with the information from the array
i have created a table but however i am not able to pass into the table why? i would like it to create a table auto if can use the table id it be great
<table id="contactinformation">
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is how i have json parse my array
const responses = JSON.parse(user.Contacts)
console.log(responses)
And get this array
This is how my array response look like
[{"ContactName": "45551134", "ContactNumber": "95011225"}]
CodePudding user response:
You can iterate through data array and append each object to a row:
const data = [{"ContactName": "45551134", "ContactNumber": "95011225"}];
const table = document.querySelector("#contactinformation");
const headers = table.querySelector("thead tr");
const body = table.querySelector("tbody");
// Create headers
for (const key in data[0]) {
const header = document.createElement("th");
header.innerText = key;
headers.append(header);
}
// Create tbody rows
data.forEach(obj => {
// Create row
const row = document.createElement("tr");
body.append(row);
// Create row element
for (const key in obj) {
const value = document.createElement("td");
value.innerText = obj[key];
row.append(value);
}
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<table id="contactinformation">
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
CodePudding user response:
is it okay to use jQuery? if yes, you can use $.each function.
const array = [{"ContactName": "45551134", "ContactNumber": "95011225"}]
$.each(array, function(index){
$("#contact-name").html(this.ContactName)
$("#contact-number").html(this.ContactNumber)
});
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<table id="contactinformation">
<thead>
<tr>
<td>Contact Name</td>
<td>Contact Number</td>
</tr>
</thead>
<tbody>
<tr>
<td id="contact-name"></td>
<td id="contact-number"></td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
