在动态构建表格时将数据插入特定列:

huangapple go评论73阅读模式
英文:

Insert data to specific column when dynamically building a table

问题

我从后端获取一个JSON格式的数据对象,需要动态构建一个表格:

data = {
   0: {'column1': 'some_data1', 'column2': 'some_data11', 'column3': 'some_data111'},
   1: {'column1': 'some_data2', 'column2': 'some_data22', 'column3': 'some_data222'},
   2: {'column1': 'some_data33', 'column2': 'some_data33', 'column3': 'some_data333'}
}

我需要将column2的数据插入到第三列,将column3的数据插入到中间列。但是当我尝试创建单元格、插入并附加数据时,出现以下错误:

在 'HTMLTableRowElement' 上执行 'insertCell' 失败:提供的值 (2) 超出了范围

我猜想这是因为该列尚不存在,当我尝试将来自column3的单元格插入到表格的第二列时,会引发错误:

let data = getData();
tbodyRef = document.getElementById("tableBody");
let newRow = tbodyRef.insertRow();

for (const [key, value] of Object.entries(data)) {
    if (key === 'column1') {
        newCell = newRow.insertCell(0);
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    } else if (key === 'column2') {
        newCell = newRow.insertCell(2);
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    } else if (key === 'column3') {
        newCell = newRow.insertCell(1); 
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    }
}

所以我认为当我执行newCell = newRow.insertCell(2);时,第三列(索引2)尚不存在。我应该怎么做?我应该首先计算对象中的列数(例如键的数量),然后循环创建空单元格,然后插入数据吗?还是有更好的方法?

英文:

I am getting a data object as JSON from the backend and I need to build a table dynamically:

data = {
   0: {'column1': 'some_data1', 'column2': 'some_data11', 'column3': 'some_data111'}
   1: {'column1': 'some_data2', 'column2': 'some_data22', 'column3': 'some_data222'}
   2: {'column1': 'some_data33', 'column2': 'some_data33', 'column3': 'some_data333'}
}

And I need to insert the data of column2 in the third column, and column3 in the middle.
But when I try to create cell, insert it and append the data, I get:

> Failed to execute 'insertCell' on 'HTMLTableRowElement': The value
> provided (2) is outside the range

I guess because the column doesn't exist yet, and when I try to insert the cell from column3 to the table's column 2 it throws the error:

let data = getData();
tbodyRef = document.getElementById("tableBody");
let newRow = tbodyRef.insertRow();

for (const [key, value] of Object.entries(data)) {
    if (key === 'column1') {
        newCell = newRow.insertCell(0);
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    } else if (key === 'column2') {
        newCell = newRow.insertCell(2);
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    } else if (key === 'column3') {
        newCell = newRow.insertCell(1); 
        cellText = document.createTextNode(value);
        newCell.appendChild(cellText);
    }
}

So I believe that when I do newCell = newRow.insertCell(2); the third column (index 2) doesn't exist yet. What should I do? Should I first count the number of columns in the object (number of keys for example), then loop to create empty cells, then insert data? Or there is a better way?

答案1

得分: 1

将数据作为纯HTML插入 - 比创建DOM元素要快得多,定义列的所需顺序并将它们映射到呈现的HTML中。此外,您可以为列数据提供格式化函数:

const data = {
   0: {'column1': 'some_data1', 'column2': 1688452200, 'column3': 'some_data111'},
   1: {'column1': 'some_data2', 'column2': 1688452200, 'column3': 'some_data222'},
   2: {'column1': 'some_data33', 'column2': 1688452200, 'column3': 'some_data333'},
};

const columns = {
  column1: null, 
  column3: null,
  column2: formatDate
};

document.querySelector('tbody').innerHTML = 
  Object
    .values(data)
    .map(row => '<tr><td>' + 
        Object.entries(columns).map(([name, fn]) => fn?.(row[name]) ?? row[name]).join('</td><td>') + 
      '</td></tr>'
    ).join('');

function formatDate(timestamp){
  const date = new Date(timestamp * 1000);
  date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  return date.toTimeString().slice(0, 8);
}
<table>
  <tbody></tbody>
</table>
英文:

Insert the data as plain HTML - much faster than creating DOM elements, define the needed order of columns and map them into a rendered HTML. Also you can provide format functions for you column data:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = {
   0: {&#39;column1&#39;: &#39;some_data1&#39;, &#39;column2&#39;: 1688452200, &#39;column3&#39;: &#39;some_data111&#39;},
   1: {&#39;column1&#39;: &#39;some_data2&#39;, &#39;column2&#39;: 1688452200, &#39;column3&#39;: &#39;some_data222&#39;},
   2: {&#39;column1&#39;: &#39;some_data33&#39;, &#39;column2&#39;: 1688452200, &#39;column3&#39;: &#39;some_data333&#39;},
};

const columns = {
  column1: null, 
  column3: null,
  column2: formatDate
};

document.querySelector(&#39;tbody&#39;).innerHTML = 
  Object
    .values(data)
    .map(row =&gt; &#39;&lt;tr&gt;&lt;td&gt;&#39; + 
        Object.entries(columns).map(([name, fn]) =&gt; fn?.(row[name]) ?? row[name]).join(&#39;&lt;/td&gt;&lt;td&gt;&#39;) + 
      &#39;&lt;/td&gt;&lt;/tr&gt;&#39;
    ).join(&#39;&#39;);
    
function formatDate(timestamp){
  const date = new Date(timestamp * 1000);
  date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  return date.toTimeString().slice(0, 8);
}

<!-- language: lang-html -->

&lt;table&gt;
  &lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月29日 20:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定