首页 > 解决方案 > 限制表中的数据数量

问题描述

我将我的数据表与 websocket 连接以显示来自后端的实时数据。数据是实时提要,因此会连续添加行。

问题:当旧数据达到例如 1000 行时,如何制作数据表以删除旧数据,因此在一个表中仅显示 1000 行?

标签: javascriptjquerydatatables

解决方案


preDraw您可以在推送新数据时重绘数据表之前监听触发的事件。因此,您可以检查是否超出行数并查找并删除最旧的条目。

我猜这可能有效:

//define initial data sample
const srcData = [{parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}];
//define datatable object
const dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  columns: [
    {title: 'parameter', data: 'parameter'},
    {title: 'value', data: 'value'},
    {title: 'timestamp', data: 'timestamp'}
  ]
});
//emulate new data insertion
const dataPooler = window.setInterval(function(){
	dataTable.row.add({parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}).draw();
},3000);
//listen for new draws, purge oldest entry
dataTable.on('preDraw', function(){
	if(dataTable.rows().count() < 5) return;
  //grab the oldest entry timestamp
	let oldestTimestamp = dataTable.column(2).data().toArray().map(entry => new Date(entry)).sort()[0].toString();
	//look through the table and purge corresponding entry if table has more than 10 entries
	let oldestEntryIndex = dataTable.column(2).data().indexOf(oldestTimestamp)
	dataTable.row(oldestEntryIndex).remove();
});
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  </head>
  <body>
    <table id="mytable"></table>
  </body>
</html>


推荐阅读