1

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

need th also dynamic. is it possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.