How to display similar JSON data in one table row

Viewed 121

I want to display similar JSON data in one row. I'm trying to compare array index with keys index and store in new array

Expected result

enter image description here

this is my code

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 Answers

As you have two column where you need to put value you can create separate JSON Array for both column where key will be same . Then, inside your each loop compare if the key matches with keys and only put value if match . Finally , to generate table you can append htmls in some variable using += and append same to your tbody.

Demo Code :

//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>

Related