如何使用JS/JQUERY从数组创建特定的表



我正在做一些项目,我被这个困了一段时间。我在数据库中有这样的表:

tbody> <<tr>
ProjectName UserName SpentDays
FirstProjectUser110
SecondProjectUser15
SecondProjectUser23
ThirdProject

我们需要reduce、map和模板文字的组合

const NULL = null; // or you use null in the object
ProjectInfo = [{
ProjectName: 'FirstProject',
UserName: 'User1',
SpentDays: 10
}, {
ProjectName: 'SecondProject',
UserName: 'User1',
SpentDays: 5
}, {
ProjectName: 'SecondProject',
UserName: 'User2',
SpentDays: 3
}, {
ProjectName: 'ThirdProject',
UserName: NULL,
SpentDays: NULL
}]
const users = [...new Set(ProjectInfo.map(({ UserName }) => UserName))].filter(user => user != NULL); // create a list of users
document.querySelector("table thead tr").innerHTML += users.map(user => `<th>${user}</th>`).join(""); // add them to the table head
// create a default object
const obj = JSON.stringify(users.reduce((acc, user) => {
acc[user] = "NULL";
return acc
}, {}));
// reduce to something more manageable 
const rows = ProjectInfo.reduce((acc, cur) => {
acc[cur.ProjectName] = acc[cur.ProjectName] || JSON.parse(obj)
if (cur.UserName !== null) acc[cur.ProjectName][cur.UserName] = cur.SpentDays
return acc
}, {});
document.querySelector("table tbody").innerHTML = Object
.entries(rows)
.map(([name,project]) => `<tr><td>${name}</td>${Object
.values(project)
.map(val => `<td>${val}</td>`)
.join("")}</tr>`)
.join("");
<link rel="stylesheet" href="https://cdn.sstatic.net/Shared/stacks.css" />
<table class="s-table">
<thead>
<tr>
<th>Projects</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

应该可以了。

别介意这个答案,我误解了OP想要的。

projectInfo = [{
ProjectName: 'FirstProject',
UserName: 'User1',
SpentDays: 10
}, {
ProjectName: 'SecondProject',
UserName: 'User1',
SpentDays: 5
}, {
ProjectName: 'SecondProject',
UserName: 'User2',
SpentDays: 3
}, {
ProjectName: 'ThirdProject',
UserName: null,
SpentDays: null
}];
var tbody = $('#mytable tbody');
projectInfo.forEach(e => {
var row = $("<tr></tr>");
row.append($("<td></td>").text(e.ProjectName));
row.append($("<td></td>").text(e.UserName));
row.append($("<td></td>").text(e.SpentDays));
tbody.append(row);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable" border=1>
<thead>
<tr>
<th>Projects</th>
<th>UserName</th>
<th>SpentDays</th>
</tr>
</thead>
<tbody>

</tbody>
</table>

最新更新