从远程JSON数组返回给定时间内的放电次数

时间:2019-01-02 04:28:11

标签: jquery json

我有一个搜索从date和date到日期以及一个带有部门的选择框。我希望部门在给定时间内从我的远程JSON数组中明智地排放(计数)并显示在HTML表格中。

这是我的远程JSON数组:

{
   "success":true,
   "dataList":[
      {
         "dischargedatetime":"2018-12-26T00:00:00",
         "DepartmentName":"Cardiology",
         "DischargeCount":3
      },
      {
         "dischargedatetime":"2018-12-25T00:00:00",
         "DepartmentName":"Cardiology",
         "DischargeCount":2
      },
      {
         "dischargedatetime":"2018-12-26T00:00:00",
         "DepartmentName":"Clinical Hematology",
         "DischargeCount":3
      }
   ]
}

这是我的网址:

getDepartmentwiseDischarge?startDate=2018-12-25&endDate=2018-12-26&departmentName=Cardiology

1 个答案:

答案 0 :(得分:0)

您可以在json上使用forEach循环并绑定到如下表。

var json = [{
  "dischargedatetime": "2018-12-26T00:00:00",
  "DepartmentName": "Cardiology",
  "DischargeCount": 3
}, {
  "dischargedatetime": "2018-12-25T00:00:00",
  "DepartmentName": "Cardiology",
  "DischargeCount": 2
}, {
  "dischargedatetime": "2018-12-26T00:00:00",
  "DepartmentName": "Clinical Hematology",
  "DischargeCount": 3
}];

var DName = [],
  DCount = [];

json.forEach(function(obj) {
  if (DName.indexOf(obj.DepartmentName) == -1)
    DName.push(obj.DepartmentName);

  var lastIndex = DName.length - 1;
  if (typeof DCount[lastIndex] == "undefined")
    DCount.push(obj.DischargeCount);
  else
    DCount[lastIndex] += obj.DischargeCount;
});
Array.prototype.associate = function(keys) {
  var result = {};

  this.forEach(function(el, i) {
    result[keys[i]] = el;
  });

  return result;
};
var datalist = DName.associate(DCount); //Make key value par after sum
var html; //Generate html for table.
$.each(datalist, function(key, val) {
  html += "<tr>"
  html += "<td>" + val + "</td>";
  html += "<td>" + key + "</td > ";
  html += "</tr>"

});
$('table').append(html);
table, th, td {
  border: 1px solid black;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>DepartmentName</th>
    <th>DischargeCount</th>
  </tr>
</table>