如何使用JSON数据创建动态表?

时间:2019-02-27 06:05:01

标签: javascript json html-table

我有一个通过JSON数据创建的HTML表,我仅在javascript的帮助下创建了表,并且表是动态的

我有一个json数组,其中有几个包含数据的对象。

我正在尝试通过此JSON创建HTML表

  • 我已经成功创建了标题,但是在创建正文部分时遇到了问题
  • 我正在尝试创建这种表:

    table

  • 平均值类似于所有已取消票据的总和除以出口数量,这就是为什么我要计算出口长度并将其存储在全局变量中的原因

  • 由于我的代码太长了,所以我已经在所有行中注释了我在做什么,在哪里遇到了什么问题
  • 在主体部分内,我不知道如何填充关于出票口的已取消票据数据,对于重复票据也是如此

这是我到目前为止所做的:

var outletCount = 0; //global variable to get the no of outlets
var data = [{
    "outlet": "JAYANAGAR",
    "cancelled": 126544,
    "duplicate": 1
  },
  {
    "outlet": "MALLESHWARAM",
    "cancelled": 31826,
    "duplicate": 31
  },
  {
    "outlet": "KOLAR",
    "cancelled": 10374,
    "duplicate": 10
  }
];

let formatData = function(data) { //outlets is unique thats why formating it to loop forward in my code
  let outlets = [];
  data.forEach(element => {
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  outletCount = outlets.length //calculating outlet count

  return {
    data: data,
    outlets: outlets,

  };
};

let renderTable = function(data) {
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById("tblOlSalesSummary");
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "Bill Type"; //header
  th.classList.add("text-center");
  headerRow.appendChild(th);
  th = document.createElement("th");
  th.innerHTML = "Average"; //header
  th.classList.add("text-center");
  headerRow.appendChild(th);
  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = element; //this one is populating outlet as header
    th.classList.add("text-center");

    headerRow.appendChild(th);

  });

  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody"); // from here onwards i don't know what to do

  let row = document.createElement("tr");

  let total = 0;
  outlets.forEach(outlet => { //i am trying to loop through outlets but getting somthing else
    let el = 0;
    data.forEach(d => {
      if (d.outlet == outlet) {
        total += parseInt(d.cancelled);
        el = d.cancelled;
      }
    });
    td = document.createElement("td");
    td.innerHTML = el.toLocaleString('en-in');
    td.classList.add("text-right");
    row.appendChild(td);
  });
  /* console.log("row is : " , row.children ) */

  tbody.appendChild(row);


  table.appendChild(tbody);
  tbl.innerHTML = "";
  tbl.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
let formatedData = formatData(data);
renderTable(formatedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div align="center" class="table table-responsive">
  <table id="tblOlSalesSummary"></table>
</div>

我不是要循环流通我已取消的账单和关于营业网点的重复账单,然后计算平均值。

3 个答案:

答案 0 :(得分:1)

我已经在此JSFiddle中编写了代码。看一看。它使用JQuery。

HTML:

<table id="dataTable">

</table>

JavaScript:

var data = [{
    "outlet": "JAYANAGAR",
    "cancelled": 126544,
    "duplicate": 1
  },
  {
    "outlet": "MALLESHWARAM",
    "cancelled": 31826,
    "duplicate": 31
  },
  {
    "outlet": "KOLAR",
    "cancelled": 10374,
    "duplicate": 10
  }
];


function draw() {
    var avgCancelled = 0;
    var avgDuplicate = 0;
    var totalCancelled = 0;
    var totalDuplicate = 0;
    for (var i = 0; i < data.length; i++) {
        totalCancelled += data[i].cancelled;
        totalDuplicate += data[i].duplicate;
    }
    avgCancelled = totalCancelled / data.length;
    avgDuplicate = totalDuplicate / data.length;
    drawTableHead()
    drawTableRows(avgCancelled, avgDuplicate)
}

function drawTableHead() {
    var row = $("<tr />");
    $("#dataTable").append(row);
    row.append("<th>" + "BILLTYPE"  + "</th>")
    row.append("<th>" + "AVERAGE"  + "</th>")
    for (var i = 0; i < data.length; i++) {
        row.append("<th>" + data[i].outlet  + "</th>")
    }
}

function drawTableRows(avgCancelled, avgDuplicate) {
    var firstRow = $("<tr />");
    $("#dataTable").append(firstRow);
    firstRow.append("<td>" + "CANCELLED BILL"  + "</td>")
    firstRow.append("<td>" + avgCancelled  + "</td>")
    for (var i = 0; i < data.length; i++) {
        firstRow.append("<td>" + data[i].cancelled  + "</td>")
    }
    var secondRow = $("<tr />");
    $("#dataTable").append(secondRow);
    secondRow.append("<td>" + "DUPLICATE BILL"  + "</td>")
    secondRow.append("<td>" + avgDuplicate  + "</td>")
    for (var i = 0; i < data.length; i++) {
        secondRow.append("<td>" + data[i].duplicate  + "</td>")
    }
}


draw();

答案 1 :(得分:1)

billtypeaverage中有两个静态字段列,需要在循环json数据之前附加

 var outletCount = 0; //global variable to get the no of outlets
var data = [{
    "outlet": "JAYANAGAR",
    "cancelled": 126544,
    "duplicate": 1
  },
  {
    "outlet": "MALLESHWARAM",
    "cancelled": 31826,
    "duplicate": 31
  },
  {
    "outlet": "KOLAR",
    "cancelled": 10374,
    "duplicate": 10
  },
  {
    "outlet": "New Test",
    "cancelled": 154,
    "duplicate": 20
  }
];

let formatData = function(data) { //outlets is unique thats why formating it to loop forward in my code
  let outlets = [];
  data.forEach(element => {
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  outletCount = outlets.length //calculating outlet count

  return {
    data: data,
    outlets: outlets,

  };
};

let renderTable = function(data) {
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById("tblOlSalesSummary");
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "Bill Type"; //header
  th.classList.add("text-center");
  headerRow.appendChild(th);
  th = document.createElement("th");
  th.innerHTML = "Average"; //header
  th.classList.add("text-center");
  headerRow.appendChild(th);
  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = element; //this one is populating outlet as header
    th.classList.add("text-center");

    headerRow.appendChild(th);

  });

  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody"); // from here onwards i don't know what to do

  let row = document.createElement("tr");

  let total = 0;

  // static field insertion for Cancelled bill
  let el = 'Cancelled bill';
  td = document.createElement("td");
  td.innerHTML = el.toLocaleString('en-in');
  td.classList.add("text-right");
  row.appendChild(td);
  // Logic start to find the average cancelled amount 
  var total_cancel =0;
  total_can_count = 0;
  outlets.forEach(outlet => { 
    data.forEach(d => {
      if (d.outlet == outlet) {
        total_cancel += parseInt(d.cancelled);
        total_can_count++;

      }
    });
  });

  let el_avg = ( total_cancel / (total_can_count) );
  td = document.createElement("td");
  td.innerHTML = el_avg.toLocaleString('en-in');
  td.classList.add("text-right");
  row.appendChild(td);
  // Logic End to find the average cancelled amount 

  outlets.forEach(outlet => { 
    let el = 0;
    data.forEach(d => {
      if (d.outlet == outlet) {
        total += parseInt(d.cancelled);
        el = d.cancelled;
      }
    });
    td = document.createElement("td");
    td.innerHTML = el.toLocaleString('en-in');
    td.classList.add("text-right");
    row.appendChild(td);
  });

  
  /* console.log("row is : " , row.children ) */

  tbody.appendChild(row);

  let row_duplicate = document.createElement("tr");

  let total_dup = 0;
  // static field insertion for duplicate bill
  let el_2 = 'Duplicate bill';
  td = document.createElement("td");
  td.innerHTML = el_2.toLocaleString('en-in');
  td.classList.add("text-right");
  row_duplicate.appendChild(td);

  // Logic start to find the Duplicate average  
  total_dup_count = 0;
  outlets.forEach(outlet => { 
    data.forEach(d => {
      if (d.outlet == outlet) {
        total_dup += parseInt(d.duplicate);
        total_dup_count++;
      }
    });
  });

  let el_avg_2 = ( total_dup / (total_dup_count) );
  td = document.createElement("td");
  td.innerHTML = el_avg_2.toLocaleString('en-in');
  td.classList.add("text-right");
  row_duplicate.appendChild(td);

  // Logic End to find the Duplicate average  

  outlets.forEach(outlet => { //i am trying to loop through outlets but getting somthing else
    let el = 0;
    data.forEach(d => {
      if (d.outlet == outlet) {
        total += parseInt(d.duplicate);
        el = d.duplicate;
      }
    });
    td = document.createElement("td");
    td.innerHTML = el.toLocaleString('en-in');
    td.classList.add("text-right");
    row_duplicate.appendChild(td);
  });


  /* console.log("row is : " , row.children ) */

  tbody.appendChild(row);
  tbody.appendChild(row_duplicate);

  table.appendChild(tbody);
  tbl.innerHTML = "";
  tbl.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
let formatedData = formatData(data);
renderTable(formatedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div align="center" class="table table-responsive">
  <table id="tblOlSalesSummary"></table>
</div>

答案 2 :(得分:0)

使用可以从json创建表的库。

示例:

https://json2html.com/

<script>
    var t = {'<>':'div','html':'${title} ${year}'};

    var d = [
        {"title":"Heat","year":"1995"},
        {"title":"Snatch","year":"2000"},
        {"title":"Up","year":"2009"},
        {"title":"Unforgiven","year":"1992"},
        {"title":"Amadeus","year":"1984"}
    ];

    document.write( json2html.transform(d,t) );
</script>