【问题标题】:Create a table in Svelte from a key list object like {col1: [cell, cell], col2: [cell, cell, cell]}在 Svelte 中从键列表对象创建一个表,例如 {col1: [cell, cell], col2: [cell, cell, cell]}
【发布时间】:2021-02-14 08:30:23
【问题描述】:

我需要一个表格,它将像下面这样的对象(数据)作为道具并创建一个表格。 我发现一些 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>

【问题讨论】:

    标签: html-table each svelte


    【解决方案1】:

    结合来自 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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      猜你喜欢
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多