Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  184] [ 1]  / answers: 1 / hits: 65848  / 9 Years ago, sun, march 29, 2015, 12:00:00

I want to display an array of objects in a dynamic table using javascript.



var rows=[{ name : John, age:20, email: [email protected]},
{ name : Jack, age:50, email: [email protected]},
{ name : Son, age:45, email: [email protected]}
........................etc
];


This is how it looks.I want to know how can I show this as a dynamic table.


More From » arrays

 Answers
97

This is how you do it:


Javascript Solution:


FIDDLE:


var rows = [{
name: "John",
age: 20,
email: "[email protected]"
}, {
name: "Jack",
age: 50,
email: "[email protected]"
}, {
name: "Son",
age: 45,
email: "[email protected]"
}];

var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
html+="<tr>";
html+="<td>"+rows[i].name+"</td>";
html+="<td>"+rows[i].age+"</td>";
html+="<td>"+rows[i].email+"</td>";

html+="</tr>";

}
html+="</table>";
document.getElementById("box").innerHTML = html;

jQuery Solution:


FIDDLE


var rows = [{
name: "John",
age: 20,
email: "[email protected]"
}, {
name: "Jack",
age: 50,
email: "[email protected]"
}, {
name: "Son",
age: 45,
email: "[email protected]"
}];

$(document).ready(function () {
var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
html+="<tr>";
html+="<td>"+rows[i].name+"</td>";
html+="<td>"+rows[i].age+"</td>";
html+="<td>"+rows[i].email+"</td>";

html+="</tr>";

}
html+="</table>";
$("div").html(html);
});

jQuery Solution 2:


FIDDLE


var rows = [{
name: "John",
age: 20,
email: "[email protected]"
}, {
name: "Jack",
age: 50,
email: "[email protected]"
}, {
name: "Son",
age: 45,
email: "[email protected]"
}];

const Array2Table = (arr) => {
let Table = [];
let top_row = [];
let rows = [];

for (let i = 0; i < arr.length; i++) {
let cells = [];

for (let property in arr[i]) {
if (top_row.length < Object.keys(arr[i]).length) {
top_row.push(`<th scope="col">${property}</th>`);
}
if (arr[i][property] === null) {
cells.push(`<td>${null}</td>`);
} else {
cells.push(`<td>${arr[i][property]}</td>`);
}
}

rows.push(`<tr>${cells.join("")}</tr>`);
}

Table.push(`<table class="table card-table table-striped">`);
Table.push(`<thead>${top_row.join("")}</thead>`);
Table.push(`<tbody>${rows.join("")}<tbody>`);
Table.push("</table>");
return Table.join("");
}

$(function() {
let html = Array2Table(rows);
$("div").html(html);
});

[#67258] Friday, March 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;