首页 > 解决方案 > 使用 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);
});

标签: javascriptjavascript-objects

解决方案


首先从对象中提取uuid属性,然后迭代其他属性。

另外,对于数组,不要迭代它,因为它们没有被使用——只需用orkeys迭代数组本身。forEachfor..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>


推荐阅读