javascript - 使用 javascript 遍历对象以生成包含表数据的表行
问题描述
目标是呈现 4 列cell
的行<td>
。然而,该对象有 5 个数据点。如何迭代对象,以便将其与在第 4 列中呈现的按钮uuid
一样呈现?value
如果有另一种方法来实现这一点而不是下面?
const obj = [
{
resident: "Lily",
date: "05/29/2020",
type: "Basketball Court",
status: "approved",
uuid: "ksjdiofjoij3i4jovoii3ni"
},{
resident: "Kyle",
date: "05/30/2020",
type: "Swimming Pool",
status: "denied",
uuid: "wiczoixmcie923fjffj23jij"
}
];
const table = document.querySelector("#table");
Object.keys(obj).forEach(key => {
let row = document.createElement("TR");
Object.entries(obj[key]).forEach(([k, v]) => {
if (k !== "uuid") {
let cell = document.createElement("TD");
if (k === "status") {
cell.innerHTML = `
<button value="` + UUIDHERE + `"class="approve-btn">Approve</button>
<button value="` + UUIDHERE + `"class="deny-btn">Deny</button>`;
} else {
cell.innerHTML = v;
}
row.appendChild(cell);
}
});
table.appendChild(row);
});
解决方案
首先从对象中提取uuid
属性,然后迭代其他属性。
另外,对于数组,不要迭代它,因为它们没有被使用——只需用orkeys
迭代数组本身。forEach
for..of
我还建议使用信息更丰富的变量名称 - yourobj
不是一个普通对象,而是一个数组,所以称之为arr
, or residentsArr
,或类似的名称,否则你可能会在以后引起你自己(和脚本的未来读者)的混淆.
const residentsArr = [
{
resident: "Lily",
date: "05/29/2020",
type: "Basketball Court",
status: "approved",
uuid: "ksjdiofjoij3i4jovoii3ni"
},{
resident: "Kyle",
date: "05/30/2020",
type: "Swimming Pool",
status: "denied",
uuid: "wiczoixmcie923fjffj23jij"
}
];
residentsArr.forEach(({ uuid, ...rest }) => {
const row = document.createElement("TR");
Object.entries(rest).forEach(([k, v]) => {
const cell = document.createElement("TD");
if (k === "status") {
cell.innerHTML = `
<button value="${uuid}" class="approve-btn">Approve</button>
<button value="${uuid}" class="deny-btn">Deny</button>`;
} else {
cell.innerHTML = v;
}
row.appendChild(cell);
});
table.appendChild(row);
});
<table id="table"></table>
推荐阅读
- ios - UIView坐标转换有异常。convertPoint: toView: 效果不好
- javascript - 如何使用 React 在后台添加 svg 图像?
- python - 为什么这个风玫瑰图不更新,而折线图或条形图很好?
- sas - 通过 ODBC 连接到 SAS 库
- hook - 在哪里可以找到 Gerrit 挂钩的批准类别 ID?
- c++ - 从基类指针派生派生类的模板类型
- c# - 来自脚本 32/34 个字符的正则表达式变量
- android - android studio中的庆祝动画
- c - 使用 getchar() 查看输入是否为有效标识符
- linux - 使用 ssh 启动远程进程并退出