【问题标题】:Display data ordered in a table显示在表格中排序的数据
【发布时间】:2021-01-02 20:46:42
【问题描述】:

我正在显示一个表格,该表格获取来自 api 的 json 格式的数据。 第一列是时间戳,但 api 没有给我排序的结果

所以问题是:如何修改我的代码以使表格中显示的行按顺序排列 根据第一列,这将是一个数字(时间戳是 UNIX 13 位)?

如果有人能帮忙,非常感谢你

【问题讨论】:

  • 你也可以加body op吗?
  • 您可以使用lodash 库按对象的属性对对象数组进行排序。对于您的情况,您可以按 body.timestampbody 数组进行排序
  • 你可以使用数据表。它提供 ajax 加载和自定义列渲染。将来很容易集成和理解。

标签: javascript html jquery json database


【解决方案1】:

由于您拥有带有时间戳(unix 13 位)的数组,您可以使用 sort 并提供一个函数来根据时间戳属性对数组进行排序。

data.sort(
  function(a,b){ 
    
    //use new Date parse string to date type
    //convert date to number use Date.parse()
    //format function(a,b) { return a-b; }
    
    return Date.parse(new Date(a.timestamp)) - Date.parse(new Date(b.timestamp)); 
  }
);

var data = [{
    timestamp: "1563398686957",
    country: "Brazil"
  },
  {
    timestamp: "1126398681149",
    country: "USA"
  },
  {
    timestamp: "1123398681149",
    country: "UK"
  },
  {
    timestamp: "1124398681149",
    country: "India"
  },
  {
    timestamp: "1163398681149",
    country: "Canada"
  }
];
$(document).ready(function() {
//sanitize data first
data.forEach(function(x) { x.timestamp = new Date(parseInt(x.timestamp))})
//sort the data
  let sortedData = data.sort(
  function(a,b){ 
    
    //use new Date parse string to date type
    //convert date to number use Date.parse()
    //format function(a,b) { return a-b; }
    
    return Date.parse(a.timestamp) - Date.parse(b.timestamp); 
  }
);

  var table = $("<table><tr><th>timestamp</th><th>country</th></tr>");
  var tr;
  for (var i = 0; i < sortedData.length; i++) {


    tr = $("<tr>");
    tr.append("<td >" + sortedData[i].timestamp.toString().substr(0,24) + "</td>");
    tr.append("<td>" + sortedData[i].country + "</td>");
    table.append(tr);
  }


  table.append("</table>");
  $("#jsonData").html(table);


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id="jsonData"></div>
</body>

【讨论】:

    【解决方案2】:

    尝试更改 json,以便在 for 命令之前每个都有一个 id 和 body.sort(),或者你可以看看这个

    https://www.w3schools.com/howto/howto_js_sort_table.asp

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 2014-05-27
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      相关资源
      最近更新 更多