在Svelte中从类似{col1:[cell,cell],col2:[cell,cell]}的键列表对象创建一个表



我需要一个表,它以下面的对象(数据(为道具,并创建一个表。我发现了一些js库可以帮助从json创建表,但我更喜欢更简单的;苗条的方式";。

我一直在生成行。

<script>
// export let data
let data = {
ignore1: 85,
ignore2: "2020-10-31",
ignore3: "some data",
ignore4: "another data",
ignore5: "../../assets/img/avatar.jpg",
col1: ["cell1", "cell1", "cell1", "cell1"],
col2: ["cell2", "cell2", "cell2", "cell2", "cell2", "cell2"],
col3: ["cell3", "cell3", "cell3"]
}

let columns = []
let values = []
for (const [col, val] of Object.entries(data)) {  
if (Array.isArray(val)) {
columns.push(col)
values.push(val)
}
}
console.log(columns)
console.log(values)
// From the list of values get the max len of a list 
let rows_len = Math.max(0, ...values.map(item => item.length))
// Normalize lists to have the same length as the biggest one in the nested lists
let rows = values.map(li => {
if (li.length != rows_len) {
let fill_arr = Array.from({length: rows_len - li.length}).map(el => "")
li.push(...fill_arr)
}
return li
})
console.log(rows)
let rows_range = Array.from({length: rows_len}).map(el => "")
</script>

<table class="w-full">
<thead class="capitalize border-b-2">
<tr>
{#each columns as col}
<td>{col}</td>
{/each}
</tr>
</thead>
<tbody>
{#each rows[0] as row, i}
<td>{row}</td>
{/each}
</tbody>
</table>

您需要在模板中使用嵌套循环。一个用于行,一个用于每行上的单元格:

<tbody>
{#each rows as row}
<tr>
{#each row as cell}
<td>{cell}</td>
{/each}
</tr>
{/each}
</tbody>

结合rixo的答案,我需要创建一个新列表,该列表一次从所有3个列表中获取每个索引,并创建另一个列表。在模板中,在html_rows而不是行上迭代。

let cols_range = Array.from({length: columns.length}).map(el => "")
let rows_range = Array.from({length: rows_len}).map(el => "")
// console.log(`${rows_range.length}rows, ${cols_range.length}cols`)
let html_rows = []
for (let ir = 0; ir < rows_range.length; ir++) {
let html_row = []
for (let ic = 0; ic < cols_range.length; ic++) {
console.log(ic, ir, rows[ic][ir])
html_row.push(rows[ic][ir])
}
html_rows.push(html_row)
}

回复:https://svelte.dev/repl/d417680037274d82b3f0fe2cd807d4a2?version=3.29.4

相关内容

  • 没有找到相关文章

最新更新