最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create dynamic table with JSON data? - Stack Overflow

programmeradmin0浏览0评论

I have a HTML table which I am making with the help of JSON data, I am creating my table with the help of javascript only and my table is dynamic

I have a array of json inside which I have several objects which are having the data.

from this JSON I am trying to make a HTML table

  • I have successfully created the header but facing issue in creating the body part
  • I am trying to create this kind of table:

  • Average is like sum of all cancelled bills divided by no.of outlet, that's why I am calculating length of outlets and storing it in a global variable

  • As my code is bit of long I have mented my all lines where I am doing what and facing what issues where
  • Inside the body part I don't know how can I populate the canceled bills data with respect to outlet and same for duplicate bills also

This is what I have done till now:

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=".3.1/jquery.min.js"></script>
<link rel="stylesheet" href=".1.2/css/bootstrap.min.css">
<div align="center" class="table table-responsive">
  <table id="tblOlSalesSummary"></table>
</div>

I have a HTML table which I am making with the help of JSON data, I am creating my table with the help of javascript only and my table is dynamic

I have a array of json inside which I have several objects which are having the data.

from this JSON I am trying to make a HTML table

  • I have successfully created the header but facing issue in creating the body part
  • I am trying to create this kind of table:

  • Average is like sum of all cancelled bills divided by no.of outlet, that's why I am calculating length of outlets and storing it in a global variable

  • As my code is bit of long I have mented my all lines where I am doing what and facing what issues where
  • Inside the body part I don't know how can I populate the canceled bills data with respect to outlet and same for duplicate bills also

This is what I have done till now:

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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn./bootstrap/4.1.2/css/bootstrap.min.css">
<div align="center" class="table table-responsive">
  <table id="tblOlSalesSummary"></table>
</div>

I am not getting the point to loop my canceled bill and duplicate bill with respect to outlets and then calculate average.

Share Improve this question edited Mar 2, 2019 at 18:10 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Feb 27, 2019 at 6:05 manish thakurmanish thakur 82010 gold badges43 silver badges82 bronze badges 1
  • Is your table layout only this one or is it dynamic? because if you want to reuse it then it might make sense to use an external library or to format your json response to be more appropriate for table formats – j4rey Commented Feb 27, 2019 at 7:06
Add a ment  | 

3 Answers 3

Reset to default 1

There were two static field column in your table billtype and average which needed to be appended before looping the json data

 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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn./bootstrap/4.1.2/css/bootstrap.min.css">
<div align="center" class="table table-responsive">
  <table id="tblOlSalesSummary"></table>
</div>

I've written the code in this JSFiddle. Take a look. It uses 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();

Use a library which can do table creation from your json.

Example:

https://json2html./

<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>
发布评论

评论列表(0)

  1. 暂无评论