如何使用JSON数据在四列中创建HTML表?

时间:2019-06-05 08:24:45

标签: javascript jquery html html-table

我有一个要用JSON数据呈现的HTML表,根据我的要求,我必须在4列中显示Data(无论数据大小如何)

问题

当我的data.length被4均分时,它显示两行四列,但是当它的长度为6时,它显示两行3-3列,这是不正确的,如果我的数据具有长度为5,那么它只显示4个项目,而不是第5个,我不知道我在犯什么错误

我的代码

var tableValue = [{
  "Item Name": "JACK DANIELS 30",
  "Quantity": 292
}, {
  "Item Name": "JACK DANIELS 750",
  "Quantity": 731
}, {
  "Item Name": "JAMESON 30",
  "Quantity": 202
}, {
  "Item Name": "JAMESON 750",
  "Quantity": 49
}, {
  "Item Name": "JIM BEAM WHITE 750",
  "Quantity": 409
}]

function addTable(tableValue) {
  var $tbl = $("<table />", {
      "class": "table table-striped table-bordered table-hover "
    }),

    $tb = $("<tbody/>"),
    $trh = $("<tr/>");


  var split = Math.round(tableValue.length / 4); // here i Think some issue
  console.log(split)
  for (i = 0; i < split; i++) {
    $tr = $("<tr/>", {
      "class": "filterData"
    });
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("<td/>", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);

      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);


}
addTable(tableValue);
.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div id="DisplayTable"></div>

在我的JSON中,我总共有Items,但它仅显示4,我已在代码中注释了我认为问题所在的行

4 个答案:

答案 0 :(得分:1)

我会简单地做到这一点:

var tableValue = [{
    "Item Name": "JACK DANIELS 30",
    "Quantity": 292
}, {
    "Item Name": "JACK DANIELS 750",
    "Quantity": 731
}, {
    "Item Name": "JAMESON 30",
    "Quantity": 202
}, {
    "Item Name": "JAMESON 750",
    "Quantity": 49
}, {
    "Item Name": "JIM BEAM WHITE 750",
    "Quantity": 409
}]

function addTable(data, columns = 4, container = "#DisplayTable") {
    var tableHtml = '';
    tableHtml += '<table class="table table-striped table-bordered">';
    tableHtml += '	<tbody>';

    var totalRows = Math.ceil(data.length / columns);
    for (let i = 0; i < totalRows; i++) {
        tableHtml += '		<tr>';
        for (let j = 0; j < columns; j++) {
            let dataIndex = i * columns + j;
            if (typeof data[dataIndex] != 'undefined') {
                tableHtml += '		<td class="text-left color' + (j + 1) + '">' + data[dataIndex]["Item Name"] + '</td>';
                tableHtml += '		<td class="text-left color' + (j + 1) + '">' + data[dataIndex]["Quantity"] + '</td>';
            } else {
                tableHtml += '		<td class="text-left color' + (j + 1) + '"></td>';
                tableHtml += '		<td class="text-left color' + (j + 1) + '"></td>';
            };
        };
        tableHtml += '		</tr>';
    };

    tableHtml += '	<tbody>';
    tableHtml += '</table>';
    $(container).html(tableHtml);
};
addTable(tableValue);
.color1 {
    background: #4AD184;
}

.color2 {
    background: #EA69EF;
}

.color3 {
    background: #E1A558;
}

.color4 {
    background: #F4F065;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="DisplayTable"></div>

也在JSFiddle上。

答案 1 :(得分:1)

您的第一个循环运行的次数比您希望的要少1倍,我不确定您的第二个循环的工作方式。将其更改为:

    for (i = 0; i <= split; i++) { // changed this
      $tr = $("<tr/>", {
        "class": "filterData"
      });
      for (j = 0; j < 4; j++) { 
        $.each(tableValue[(i*4) + j], function(key, value) { // changed this
            console.log(j)
          $("<td/>", {
            "class": "text-left color" + (j + 1)
          }).html(value).appendTo($tr);

        });
      }

答案 2 :(得分:0)

数组中的每个对象都有4个条目,因此要填充4列,每个对象将用具有键的键1和3以及值的键2和4填充一行。演示中将对详细信息进行评论。

const data = [{
  "Item Name": "JACK DANIELS 30",
  "Quantity": 292
}, {
  "Item Name": "JACK DANIELS 750",
  "Quantity": 731
}, {
  "Item Name": "JAMESON 30",
  "Quantity": 202
}, {
  "Item Name": "JAMESON 750",
  "Quantity": 49
}, {
  "Item Name": "JIM BEAM WHITE 750",
  "Quantity": 409
}];

/** genTable(selector, [...array]) 
@Param: selector [String]: element to append table to
        [...array][Array]: copy of the array of objeccts
*/
//A - Append htmlString of table to the given element
/*B - for...of loop of the given array by static method .entries()
      [index, object] destructed assignment allows easy access
      */
/*C - $('table')[0] is a jQ Object dereferenced to a jS Object
      in order to use the JS method .insertRow()
      */
//D - Same as B but with Object.entries() on each object of array
/*E - On each key/value  pair of current object .insertCell()
      and assign the text of each cell with the key then the value
      */
function genTable(selector, [...array]) {
  $(selector).append(`<table class='table table-striped table-bordered table-hover'><tbody></tbody></table>`); //A

  for (let [index, object] of array.entries()) { //B
    let row = $('table')[0].insertRow(); //C
    for (let [key, value] of Object.entries(object)) { //D
      row.insertCell().textContent = key; //E
      row.insertCell().textContent = value; //E
    }
  }
}

genTable('main', [...data])
tr td:first-of-type {
  background: #4AD184;
}

tr td:nth-of-type(2) {
  background: #EA69EF;
}

tr td:nth-of-type(3) {
  background: #E1A558;
}

tr td:last-of-type {
  background: #F4F065;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

<main></main>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

答案 3 :(得分:0)

var tableValue = [{
  "Item Name": "JACK DANIELS 30",
  "Quantity": 292
}, {
  "Item Name": "JACK DANIELS 750",
  "Quantity": 731
}, {
  "Item Name": "JAMESON 30",
  "Quantity": 202
}, {
  "Item Name": "JAMESON 750",
  "Quantity": 49
}, {
  "Item Name": "JIM BEAM WHITE 750",
  "Quantity": 409
}, {
  "Item Name": "JAMESON 750",
  "Quantity": 49
}, {
  "Item Name": "JIM BEAM WHITE 750",
  "Quantity": 409
}]

function addTable(tableValue) {
   var  container =  $( "#DisplayTable" );     
   $.each(tableValue, function(key, value) {       
     
      var item = $('<div />', { 'class': 'item' }).appendTo(container);
      var Name = $('<div />', { 'text': value["Item Name"]}).appendTo(item);
       var Quantity = $('<div />', { 'text': value["Quantity"],'class':'count'}).appendTo(item);   
     
       
  });
    
}

$( document ).ready(function() {
 addTable(tableValue);
});
#DisplayTable{

display:grid;
grid-template-columns: auto auto auto auto;



}
.item{
border:1px solid white;
display:flex;
align-items:center;
padding:10px;
border-radius:3px;
background:yellow;
color:#fff;
} 
.count{
font-weight:500;
font-size:3em;
}
.item:nth-child(4n-7) {
  background-color:green;
}

.item:nth-child(4n-6) {
  background-color:red;
}

.item:nth-child(4n-5) {
   background-color:blue;
}

.item:nth-child(4n-4) {
   background-color:black; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<div id="DisplayTable"></div>

使用Grid和flex代替表格。如果要避免使用Grid,请使用column-count。查看代码段。