从对象数组以特定方式显示表

时间:2019-09-22 14:00:09

标签: jquery html

我有一个对象数组,我想以特定格式在表中显示数据。 我想以这种格式显示表格。

enter image description here

但是我无法实现。有人可以帮我吗?

下面是对象

    var data = [
     { 
       1 :[ 
           {
        process:"p1",
        value:-6
     },
    {
        process: "p1",
        value: 5
    },
    {
        process: "p1",
        value: 10
    },
    {
        process: "p1",
        value: -3
    }

    ],
    2: [
        {
            process: "p2",
            value: 5
        },
        {
            process: "p2",
            value: 15
        },
        {
            process: "p2",
            value: 24
        },
        {
            process: "p2",
            value: -56
        }

    ]
 }
]

2 个答案:

答案 0 :(得分:2)

您可以使用$.each遍历数据,然后在循环下获取每次迭代的值,然后将值附加到同一变量(即table,最后将append数据附加到任何div。代码:

var data = [{
  "1": [{
      "process": "p1",
      "value": -6
    },
    {
      "process": "p1",
      "value": 5
    },
    {
      "process": "p1",
      "value": 10
    },
    {
      "process": "p1",
      "value": -3
    }

  ],
  "2": [{
      "process": "p2",
      "value": 5
    },
    {
      "process": "p2",
      "value": 15
    },
    {
      "process": "p2",
      "value": 24
    },
    {
      "process": "p2",
      "value": -56
    }

  ]
}];
var table = "<table class='table table-bordered'> <thead><tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th></tr> </thead>";
//looping through data
$.each(data, function(i, e) {
  $.each(e, function(key, arr) {

    table += "   <tbody>";
    //here key can be 1 or 2 i.e 1=> p1 and 2=> p2
    if (key == 1)
      table += "<tr><th>P1+</th>";
    else
      table += "<tr><th>P2+</th>";
    //looping through data in array i.e : value and proccess
    $.each(arr, function(index, obj) {

      //append data to variable
      table += "<td>" + (obj.value) + "</td>";

    });
    table += "</tr>";
  });
})
table += " </tbody><table>";
//append variable to id = "table"
$("#table").append(table);
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
  <div id="table">
  </div>
</div>

答案 1 :(得分:1)

.each()选项很好,但是您可以使用我认为更简单的东西。模板文字对此非常有用。

例如,在javascript中启动字符串

let string = "<table><tr><th>header 1</th><th>header2></tr>";

然后循环,或者对于小型表,只需手动编写代码并添加到字符串中即可。

string = string.concat(`<tr><td>${array[i].object.value1}</td><td>${array[i].object.value2}</td></tr>`);

这将是解决您的问题的简便方法。

您将必须使用append或innerHTML将HTML放置在具有JavaScript的页面上。

玩得开心!