如何在一个表格行中显示相似的 JSON 数据

时间:2021-01-22 05:38:55

标签: javascript html jquery arrays json

我想在一行中显示类似的 JSON 数据。 我正在尝试将 array indexkeys index 进行比较并存储在新的 array

预期结果

enter image description here

这是我的代码

var array = [{ "english 1": "1", "english 2": "2", "hindi 1": "1", "hindi 2": "2", "gujarati 1": "1", "gujarati 2": "2", "marathi 1": "1", "marathi 2": "2" }]
keys = ['english', 'hindi', 'gujarati', 'marathi'],
grouped = {};

$.each(array, function (i, v) {
    $.each(keys,function (ii, vv) {
        var o = {};
        o[vv] = v[vv];
        grouped[vv] = grouped[vv] || [];
        grouped[vv].push(o);
    });
});
        
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableData" class="table">
        <thead>
            <tr>
                <th>Language</th>
                <th>col 1</th>
                <th>col 2</th>
            </tr>
        </thead>
        <tbody id="showData">

        </tbody>
    </table>

1 个答案:

答案 0 :(得分:1)

由于您有两列需要放置值,您可以为两列创建单独的 JSON Array ,其中键相同。然后,在您的每个循环中比较 key 是否与 keys 匹配,如果匹配则只放置值。最后,要生成表格,您可以使用 += 在某个变量中附加 html,并将其附加到您的 tbody。

演示代码

//suppose your json look like below :
var array = [{
  english: "1",
  hindi: "1",
  gujarati: "1",
  marathi: "1"
}, {
  hindi: "2",
  gujarati: "2",
  marathi: "2",
  english: "2"
}]

keys = ['english', 'hindi', 'gujarati', 'marathi'],
  grouped = [];

$.each(keys, function(i, v) {
  var o = {}; //create  obj
  o[v] = new Array() //create array with particular key
  $.each(array, function(ii, vv) {
    o[v].push(vv[v]) //push value only when key matches
  });
  grouped.push(o); //push array inside outer array
});
var htmls = "";
$.each(grouped, function(i) {
  $.each(grouped[i], function(key, val) {
    htmls += "<tr><td>" + key + "</td><td>" + val[0] + "</td><td>" + val[1] + "</td></tr>"; //generate htmls..
  });
});

$("#showData").html(htmls) //add same to tbody
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableData" class="table">
  <thead>
    <tr>
      <th>Language</th>
      <th>col 1</th>
      <th>col 2</th>
    </tr>
  </thead>
  <tbody id="showData">

  </tbody>
</table>