Данные таблицы HTML не заполняются в правильном порядке - PullRequest
2 голосов
/ 14 марта 2019

У меня есть таблица HTML из данных JSON, Моя таблица немного сложна, я выполнил почти всю работу, но столкнулся с проблемами в некоторых областях

Это один мой JSON-объект, который я получаю

{
    "outlet": "S0009",  //this one is outlet
    "brandcode": "B0003",//brandCode by which i am looping tbody to populate brand name
    "brandname": "Finished Goods",
    "transactionType": "TransferIn", //this shows transaction type TransferIn or Sales
    "netamount": 12740 // this is the net amount
  },
{
    "outlet": "S0009",
    "brandcode": "NA",//when brandcode and brand name are NA and transactionType is Sales
    "brandname": "NA",//i want to populates the netamount of this object in Sales column
    "transactionType": "Sales",
    "netamount": 421079
  }
  • Для лучшего понимания я показал два объекта моего json, например, как они
  • Это тип таблицы, которую я пытаюсь составить this
  • У меня есть несколько данных в качестве объекта в моем JSON, которые имеют brandcode and brandname as NA и transactionType как sales, поэтому, когда возникает это условие, я хочу показать netamount в столбце места продаж, который в настоящее время я жестко кодирую как net amount outlet wise
  • Некоторое время он собирает данные другим способом, я должен поставить 0, как на моем изображении, у меня нет продаж на выходе S0010, поэтому должен показывать 0
  • То же, что и когда transactionType==sales для выхода S0010 Я должен показать столбец grnEntery, так как 0 Grn entery - это не что иное, как transactionType==TransferIn

Мой код

var data = [{
    "outlet": "S0001",
    "brandcode": "B0002",
    "brandname": "Bakery FG",
    "transactionType": "TransferIn",
    "netamount": 5810
  },
  {
    "outlet": "S0001",
    "brandcode": "B0003",
    "brandname": "Finished Goods",
    "transactionType": "TransferIn",
    "netamount": 5895
  },
  {
    "outlet": "S0001",
    "brandcode": "B0004",
    "brandname": "Pastry & Cake FG",
    "transactionType": "TransferIn",
    "netamount": 162810
  },
  {
    "outlet": "S0001",
    "brandcode": "B0005",
    "brandname": "Ice Cream FG",
    "transactionType": "TransferIn",
    "netamount": 281591
  },
  {
    "outlet": "S0001",
    "brandcode": "B0006",
    "brandname": "North Indian FG",
    "transactionType": "TransferIn",
    "netamount": 3824
  },
  {
    "outlet": "S0001",
    "brandcode": "NA",
    "brandname": "NA",
    "transactionType": "Sales",
    "netamount": 1760544
  },
  {
    "outlet": "S0002",
    "brandcode": "B0002",
    "brandname": "Bakery FG",
    "transactionType": "TransferIn",
    "netamount": 7848
  },
  {
    "outlet": "S0002",
    "brandcode": "B0003",
    "brandname": "Finished Goods",
    "transactionType": "TransferIn",
    "netamount": 6970
  },
  {
    "outlet": "S0002",
    "brandcode": "B0004",
    "brandname": "Pastry & Cake FG",
    "transactionType": "TransferIn",
    "netamount": 136450
  },
  {
    "outlet": "S0002",
    "brandcode": "B0005",
    "brandname": "Ice Cream FG",
    "transactionType": "TransferIn",
    "netamount": 242644
  },
  {
    "outlet": "S0002",
    "brandcode": "B0006",
    "brandname": "North Indian FG",
    "transactionType": "TransferIn",
    "netamount": 8618
  },
  {
    "outlet": "S0002",
    "brandcode": "NA",
    "brandname": "NA",
    "transactionType": "Sales",
    "netamount": 332872
  },
  {
    "outlet": "S0009",
    "brandcode": "B0002",
    "brandname": "Bakery FG",
    "transactionType": "TransferIn",
    "netamount": 15468
  },
  {
    "outlet": "S0009",
    "brandcode": "B0003",
    "brandname": "Finished Goods",
    "transactionType": "TransferIn",
    "netamount": 12740
  },
  {
    "outlet": "S0009",
    "brandcode": "B0004",
    "brandname": "Pastry & Cake FG",
    "transactionType": "TransferIn",
    "netamount": 256030
  },
  {
    "outlet": "S0009",
    "brandcode": "B0005",
    "brandname": "Ice Cream FG",
    "transactionType": "TransferIn",
    "netamount": 389645
  },
  {
    "outlet": "S0009",
    "brandcode": "B0006",
    "brandname": "North Indian FG",
    "transactionType": "TransferIn",
    "netamount": 8778
  },
  {
    "outlet": "S0009",
    "brandcode": "NA",
    "brandname": "NA",
    "transactionType": "Sales",
    "netamount": 421079
  },
  {
    "outlet": "S0010",
    "brandcode": "B0006",
    "brandname": "North Indian FG",
    "transactionType": "TransferIn",
    "netamount": 50
  }
]


let formatData = function(data) {
  let brandnames = [];
  let outlets = [];
  data.forEach(element => {
    if (brandnames.indexOf(element.brandname) == -1 && (element.brandname) !== "NA") { //taking brandname which do not have bradname===NA
      brandnames.push(element.brandname);
    }
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  return {
    data: data,
    brandnames: brandnames,
    outlets: outlets,
  };
};

let renderTable = function(data) {
  brandnames = data.brandnames;
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById("ConsumptionTable");
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "BillDate";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  let grandTotal = 0;
  let grandNetAmount = 0;
  let outletWiseTotal = {};
  let outletWiseNetamount = {};
  th = document.createElement("th");
  th.colSpan = 2;
  th.innerHTML = "Total";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  outlets.forEach(element => {

    th = document.createElement("th");
    th.colSpan = 2;
    th.innerHTML = element; // populating outlet i.e S0001,S0002,S0003 and S0009
    th.classList.add("text-center");
    headerRow.appendChild(th);
    outletWiseTotal[element] = 0;
    data.forEach(el => {
      if (el.outlet == element && el.brandname !== "NA") { //taking brandname which do not have bradname===NA
        outletWiseTotal[element] += parseInt(el.netamount); //here i am calculating the outletWiseTotal where transcationType==TransferIn
      }
    });
    grandTotal += outletWiseTotal[element]; //then calculating grand total to populate it into  Total column at grn entery
  });

  thead.appendChild(headerRow);
  headerRow = document.createElement("tr");
  th = document.createElement("th");
  th.innerHTML = "";
  headerRow.appendChild(th);

  for (i = 0; i < outlets.length + 1; i++) {
    th = document.createElement("th");
    th.innerHTML = "Sales";
    th.classList.add("text-center");
    headerRow.appendChild(th);

    th = document.createElement("th");
    th.innerHTML = "Grn Entery";
    th.classList.add("text-center");
    headerRow.appendChild(th);
  }

  headerRow.insertBefore(th, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);
  headerRow = document.createElement("tr");
  td = document.createElement("th");
  td.innerHTML = "Total";
  td.classList.add("text-center");
  headerRow.appendChild(td);
  let el1 = 0;
  outlets.forEach(element => {

    td = document.createElement("th");
    td.innerHTML = outletWiseTotal[element].toLocaleString('en-IN'); //populating outletWiseTotal
    console.log(outletWiseTotal[element])
    td.classList.add("text-right");
    headerRow.appendChild(td);
    if (element.outlet == element) {
      el1 = element.netAmount;
    }
    td = document.createElement("th");
    td.innerHTML = "net amount outlet wise "; //here i want to put amount where transactionType==sales for outlet wise
    td.classList.add("text-right");
    headerRow.appendChild(td);

  });
  td = document.createElement("th");
  td.innerHTML = "Total netamount"; //here sum of all outlet's netamount where transactionType==sales
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);

  td = document.createElement("th");
  td.innerHTML = grandTotal.toLocaleString('en-IN'); //populating grand total of grnentery in Total column
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody");
  brandnames.forEach(element => {
    let row = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = element; //populating brandName here i am getting NA as a row which i don't want
    row.appendChild(td);
    let total = 0;
    let totalBCount = 0;
    outlets.forEach(outlet => {
      let el = 0;
      let bc = 0;
      data.forEach(d => {
        if (d.brandname == element && d.outlet == outlet) {
          total += parseInt(d.netamount); //calculating total column grn entery
          el = d.netamount;
          bc = d.billcount;
        }
      });
      td = document.createElement("td");
      td.innerHTML = el.toLocaleString('en-IN'); //populating grnEntery for all outlet wise
      td.classList.add("text-right");
      row.appendChild(td);
      td = document.createElement("td");
      td.innerHTML = "0%";
      td.classList.add("text-right");
      row.appendChild(td);
    });
    td = document.createElement("td");
    td.innerHTML = "0%";
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);
    td = document.createElement("td");
    td.innerHTML = total.toLocaleString('en-IN'); //populating grnentery for Total column

    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);
    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">
  <table id=ConsumptionTable>
  </table>
</div>
  • Поскольку мой код немного длинен, я прокомментировал важные строки, выполняющие основную работу
  • Пожалуйста, не считайте длинным кодом, или я предоставил всю информацию, и если у кого-то возникнут сомнения, пожалуйста, уточните мне
  • Я застрял здесь некоторое время
  • Любое руководство будет полезно, спасибо заранее

Редактировать обновление : теперь я не беру строку, которая имеет фирменное наименование: "NA", вы все можете проверить фрагмент

1 Ответ

0 голосов
/ 14 марта 2019

Я сделал это самостоятельно, поэтому выкладываю ответ, на случай, если в будущем кто-нибудь столкнется с подобной проблемой

  • Я прокомментировал все строки, что я делаю, где

var data = [{
  "outlet": "S0001",
  "brandcode": "B0002",
  "brandname": "Bakery FG",
  "transactionType": "TransferIn",
  "netamount": 5810
}, {
  "outlet": "S0001",
  "brandcode": "B0003",
  "brandname": "Finished Goods",
  "transactionType": "TransferIn",
  "netamount": 5895
}, {
  "outlet": "S0001",
  "brandcode": "B0004",
  "brandname": "Pastry \u0026 Cake FG",
  "transactionType": "TransferIn",
  "netamount": 162810
}, {
  "outlet": "S0001",
  "brandcode": "B0005",
  "brandname": "Ice Cream FG",
  "transactionType": "TransferIn",
  "netamount": 281591
}, {
  "outlet": "S0001",
  "brandcode": "B0006",
  "brandname": "North Indian FG",
  "transactionType": "TransferIn",
  "netamount": 3824
}, {
  "outlet": "S0001",
  "brandcode": "NA",
  "brandname": "NA",
  "transactionType": "Sales",
  "netamount": 2019990
}, {
  "outlet": "S00011",
  "brandcode": "NA",
  "brandname": "NA",
  "transactionType": "Sales",
  "netamount": 100
}, {
  "outlet": "S0002",
  "brandcode": "B0002",
  "brandname": "Bakery FG",
  "transactionType": "TransferIn",
  "netamount": 7848
}, {
  "outlet": "S0002",
  "brandcode": "B0003",
  "brandname": "Finished Goods",
  "transactionType": "TransferIn",
  "netamount": 6970
}, {
  "outlet": "S0002",
  "brandcode": "B0004",
  "brandname": "Pastry \u0026 Cake FG",
  "transactionType": "TransferIn",
  "netamount": 136450
}, {
  "outlet": "S0002",
  "brandcode": "B0005",
  "brandname": "Ice Cream FG",
  "transactionType": "TransferIn",
  "netamount": 242644
}, {
  "outlet": "S0002",
  "brandcode": "B0006",
  "brandname": "North Indian FG",
  "transactionType": "TransferIn",
  "netamount": 8618
}, {
  "outlet": "S0002",
  "brandcode": "NA",
  "brandname": "NA",
  "transactionType": "Sales",
  "netamount": 394016
}, {
  "outlet": "S0009",
  "brandcode": "B0002",
  "brandname": "Bakery FG",
  "transactionType": "TransferIn",
  "netamount": 15468
}, {
  "outlet": "S0009",
  "brandcode": "B0003",
  "brandname": "Finished Goods",
  "transactionType": "TransferIn",
  "netamount": 12740
}, {
  "outlet": "S0009",
  "brandcode": "B0004",
  "brandname": "Pastry \u0026 Cake FG",
  "transactionType": "TransferIn",
  "netamount": 256030
}, {
  "outlet": "S0009",
  "brandcode": "B0005",
  "brandname": "Ice Cream FG",
  "transactionType": "TransferIn",
  "netamount": 389645
}, {
  "outlet": "S0009",
  "brandcode": "B0006",
  "brandname": "North Indian FG",
  "transactionType": "TransferIn",
  "netamount": 8778
}, {
  "outlet": "S0009",
  "brandcode": "NA",
  "brandname": "NA",
  "transactionType": "Sales",
  "netamount": 482861
}, {
  "outlet": "S0010",
  "brandcode": "B0006",
  "brandname": "North Indian FG",
  "transactionType": "TransferIn",
  "netamount": 50
}]


let formatData = function(data) {
  let brandnames = [];
  let outlets = [];
  data.forEach(element => {
    if (brandnames.indexOf(element.brandname) == -1 && (element.brandname) !== "NA") { //taking brandname which do not have bradname===NA
      brandnames.push(element.brandname);
    }
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  return {
    data: data,
    brandnames: brandnames,
    outlets: outlets,
  };
};
var totalSalesPercentage = '';
var olWiseSalesPercentage = '';
let renderTable = function(data) {
  brandnames = data.brandnames;
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById("ConsumptionTable");
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "BillDate";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  let grandTotal = 0;
  let grandNetAmount = 0;
  let outletWiseTotal = {};
  let outletWiseNetamount = {};
  th = document.createElement("th");
  th.colSpan = 2;
  th.innerHTML = "Total";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  outlets.forEach(element => {

    th = document.createElement("th");
    th.colSpan = 2;
    th.innerHTML = element; // populating outlet i.e S0001,S0002,S0003 and S0009
    th.classList.add("text-center");
    headerRow.appendChild(th);
    outletWiseTotal[element] = 0;
    data.forEach(el => {
      if (el.outlet == element && el.brandname !== "NA") { //taking brandname which do not have bradname==NA
        outletWiseTotal[element] += parseInt(el.netamount); //here i am calculating the outletWiseTotal where transcationType==TransferIn

      }
      if (el.outlet == element && el.brandname == "NA" && el.transactionType == "Sales") { //taking brandname which do not have bradname==NA
        outletWiseNetamount[element] = parseInt(el.netamount) || 0 //outlet wise netamount where transactiontype=="sales"


      }

    });
    grandTotal += outletWiseTotal[element]; //then calculating grand total to populate it into  Total column at grn entery

    grandNetAmount += outletWiseNetamount[element] || 0 //calculating grandTotal top put in Total column

  });

  thead.appendChild(headerRow);
  headerRow = document.createElement("tr");
  th = document.createElement("th");
  th.innerHTML = "";
  headerRow.appendChild(th);

  for (i = 0; i < outlets.length + 1; i++) {
    th = document.createElement("th");
    th.innerHTML = "Sales";
    th.classList.add("text-center");
    headerRow.appendChild(th);

    th = document.createElement("th");
    th.innerHTML = "Grn Entery";
    th.classList.add("text-center");
    headerRow.appendChild(th);
  }

  headerRow.insertBefore(th, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  headerRow = document.createElement("tr");
  td = document.createElement("th");
  td.innerHTML = "Total";
  td.classList.add("text-center");
  headerRow.appendChild(td);
  let el1 = 0;
  outlets.forEach(element => {

    td = document.createElement("th");
    td.innerHTML = outletWiseTotal[element].toLocaleString('en-IN'); //populating olwise netamount where transcation type=="Sales"
    td.classList.add("text-right");
    headerRow.appendChild(td);
    if (element.outlet == element) {
      el1 = element.netAmount;
    }
    td = document.createElement("th");
    td.innerHTML = outletWiseNetamount[element] || 0; //population sum of netamount ol wise in total column
    td.classList.add("text-right");
    headerRow.appendChild(td);

  });
  td = document.createElement("th");
  td.innerHTML = grandNetAmount;
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);

  td = document.createElement("th");
  td.innerHTML = grandTotal.toLocaleString('en-IN');
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody");
  brandnames.forEach(element => {
    let row = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = element;
    row.appendChild(td);
    let total = 0;
    let totalBCount = 0;
    outlets.forEach(outlet => {
      let el = 0;
      let bc = 0;
      data.forEach(d => {
        if (d.brandname == element && d.outlet == outlet) {
          total += parseInt(d.netamount);
          el = d.netamount;
        }
      });

      olWiseSalesPercentage = (el / outletWiseTotal[outlet]) * 100 || 0
      td = document.createElement("td");
      td.innerHTML = el.toLocaleString('en-IN');

      td.classList.add("text-right");
      row.appendChild(td);
      td = document.createElement("td");
      td.innerHTML = olWiseSalesPercentage.toFixed(2) + "%";

      td.classList.add("text-right");
      row.appendChild(td);
    });
    totalSalesPercentage = (total / grandTotal) * 100
    const totalSalesPercentageFix = totalSalesPercentage.toFixed(2) + "%"
    td = document.createElement("td");
    td.innerHTML = totalSalesPercentageFix;
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);

    td = document.createElement("td");
    td.innerHTML = total.toLocaleString('en-IN');
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);
    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">
  <table id=ConsumptionTable>
  </table>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...