可以使用Object.keys()方法获取对象的键值数组,然后根据这个数组渲染表格。
示例代码:
const data = [
{id: 1, name: 'Alice', age: 23},
{id: 2, name: 'Bob', age: 32},
{id: 3, name: 'Charlie', age: 45}
];
const renderTable = (data) => {
const headers = Object.keys(data[0]); // 获取第一个对象的键值数组作为表格头部
const tableHeaders = headers.map(header => `${header} `).join(''); // 将表头拼接成字符串
const tableBody = data.map(row => { // 遍历每一行数据
const rowData = headers.map(header => `${row[header]} `).join(''); // 根据键值获取对应数据
return `${rowData} `; // 将行数据拼接成字符串
}).join('');
const table = `
${tableHeaders}
${tableBody}
`; // 将表头和表体拼接成完整的表格
return table;
};
const table = renderTable(data);
console.log(table);
输出结果:
id
name
age
1 Alice 23
2 Bob 32
3 Charlie 45
下一篇:不知道键(s)的通用过滤函数