Hari
Hari

Reputation: 43

How to Create dynamic table with json object using jquery

I have json like below.I have to generate dynamic th with json key. and generate tr and td with its value.How to achive this.

let jsonObj= {
       "No of cells":[
          "65",
          "65",
       ],
       "Current density":{
          "Unit":"A/cm2",
          "Values":[
             "0.2",
             "0.4",
          ]
       }
       
    }

I need table like

<table>
<th>No of cells</th>
<th>Current density</th>
<tr>
<td>65</td>
<td>0.2</td>
</tr>
<tr>
<td>65</td>
<td>0.4</td>
</tr>
</table>

I Have tried like this:

var idx =0;
for(let key in jsonObj){
console.log(key)
// for(let key in jsonObj){
    var row = "<tr>";
  row += "<td>" + jsonObj[key] + "</td>";
  row += "<td>" + jsonObj[key][idx] + "</td>";
  row += "<td>" + jsonObj[key][idx] + "</td>";
  row += "</tr>";
idx++;
$("#data").append(row);

// }

}

But this not working.Please Help me

Upvotes: 1

Views: 1115

Answers (1)

Harshana
Harshana

Reputation: 5476

Assuming that the two Keys in the JSON Object has same number of values. You can use the following solution to fulfill your task.

let jsonObj = {
  "No of cells": [
    "65",
    "65",
  ],
  "Current density": {
    "Unit": "A/cm2",
    "Values": [
      "0.2",
      "0.4",
    ]
  }

}
var row = "";
for (let key in jsonObj){
  row += `<th>${key}</th>`;
}

$("#data").append(row);

row = "";

for (let idx in jsonObj["No of cells"]) {
  var row = "<tr>";
  row += "<td>" + jsonObj["No of cells"][idx] + "</td>";
  row += "<td>" + jsonObj["Current density"]["Values"][idx] + "</td>";
  row += "</tr>";
  
  $("#data").append(row);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">

</table>

Upvotes: 2

Related Questions