0

I have gone through this solution Parsing JSON objects for HTML table . But in this solution Object keys are pre-defined when creating table. But I have some json data which can have random data.

Somtimes it can be :

var data = {
"C#": 2172738,
"CSS": 9390,
"HTML": 135085,
"Java": 337323
}

Or, Sometimes it can be:

var data = {
"Go": 2172738,
"Ruby": 9390,
"Dart": 135085
}

That means keys are not fixed. That data object can be dynamic. I want to convert the dynamic object to html table. Let's say, I have a table where thead is defined and tbody is empty:

<table id="_myTable">
 <thead>
  <th>Language</th>
  <th>Line of Codes</th>
</thead>
  <tbody>
  </tbody>
</table>

How should I approach to insert that dynamic object data to tbody.

Shunjid Rahman
  • 409
  • 5
  • 17

2 Answers2

0

You can use Object.keys(data) to get all of keys for "language" table data and Object.values(data) or Object.keys(data).map(key => data[key]) for "line of codes" table data.

Ampersanda
  • 2,016
  • 3
  • 21
  • 36
0

You can use for...in, Template literals and element.insertAdjacentHTML(position, text); to accomplish your task:

var data = {
    "C#": 2172738,
    "CSS": 9390,
    "HTML": 135085,
    "Java": 337323
}
for (key in data) {
    var tr = `<tr><td>${key}</td><td>${data[key]}</td></tr>`;
    document.querySelector('#_myTable tbody').insertAdjacentHTML('beforeend', tr);
}
<table id="_myTable">
    <thead>
    <th>Language</th>
    <th>Line of Codes</th>
    </thead>
    <tbody>
    </tbody>
</table>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61