Home > Enterprise >  How to loop through an array of JSON using for loop in javascript and make a table row using it
How to loop through an array of JSON using for loop in javascript and make a table row using it

Time:11-15

I do have this sample array of JSON, and I do not know how to loop through them and use it in creating a table row.

Sample code:


var data = [
   {foo1:"a",foo2:"b",foo3:"c"},
   {foo1:"d",foo2:"e",foo3:"f"},
   {foo1:"g",foo2:"h",foo3:"i"}
]

I did use this method:

 $.each(data, function (key, value) {
        rows  = "<tr id="   key   "><td>"   value.foo1  "</td><td>"   value.foo2  "</td><td>"   value.foo3     "</td><td>"</tr>";
        });

//But I want to make it more flexible, so that I can reuse it in making another rows from another array of JSON, like this scenario:

var dataNew = [
   {lorem1:"j",lorem2:"k",lorem3:"l"},
   {lorem1:"m",lorem2:"n",lorem3:"o"},
   {lorem1:"p",lorem2:"q",lorem3:"r"},
   {lorem1:"x",lorem2:"s",lorem3:"t"},
   {lorem1:"w",lorem2:"y",lorem3:"z"}
]

//Now I cannot use the method above

CodePudding user response:

We can use Object.entries() to get the key and value dynamiclly

var data = [
   {foo1:"a",foo2:"b",foo3:"c"},
   {foo1:"d",foo2:"e",foo3:"f"},
   {foo1:"g",foo2:"h",foo3:"i"}
]

var dataNew = [
   {lorem1:"j",lorem2:"k",lorem3:"l"},
   {lorem1:"m",lorem2:"n",lorem3:"o"},
   {lorem1:"p",lorem2:"q",lorem3:"r"},
   {lorem1:"x",lorem2:"s",lorem3:"t"},
   {lorem1:"w",lorem2:"y",lorem3:"z"}
]

const parseData = (data,table) => {
  let rows = "";
  data.forEach(d1 =>{
    rows  = "<tr>"
    Object.entries(d1).forEach(d2 => {
     rows  = "<td id='"   d2[0]   "'>"   d2[1]   "</td>" 
    })
    rows  ="</tr>"
  })

  table.innerHTML = rows
}

parseData(data,document.querySelector("#table1"))
parseData(dataNew,document.querySelector("#table2"))
<table border="1" id="table1">
<table>
<br/>
<table border="1" id="table2">
<table>

CodePudding user response:

You can collect the possible keys that appear in the objects that you have in array. Then iterate over original array of objects and inside iterate over array of keys to get the values and create the rows.

Functional Correctness

Collecting the keys first is required, because JavaScript does not guarantee the order of properties within the object. If you know that each object in the array have the same properties, you may collect keys from the first object only, instead of iterating over all items.

Security

Also, notice that creating DOM elements by concatenating strings is not secure, since this approach is vulnerable to code injections. Assigning values to .textContent property of DOM Elements sanitizes the content.

var dataNew = [
   {lorem1:"j",lorem2:"k",lorem3:"l"},
   {lorem3:"o",lorem1:"m",lorem2:"n"},
   {lorem2:"q",lorem1:"p",lorem3:"r"},
   {lorem1:"x",lorem2:"s",lorem3:"t"},
   {lorem1:"w",lorem3:"z",lorem2:"y"}
]

function renderTable(table, data) {

  // Collect unique keys
  var keys = Array.from(
    data.reduce((acc, cur) => {
      Object.keys(cur).forEach(key => acc.add(key));
      return acc;
    }, new Set())
  );
  
  // Columns
  var columns = document.createElement('tr');
  keys.forEach(key => {
    var th = document.createElement('th');
    th.textContent = key;
    columns.appendChild(th);
  });
  table.appendChild(columns);

  // Rows
  data.forEach((row, idx) => {
    var tr = document.createElement('tr');
    tr.setAttribute('id', 'row-' idx);
    keys.forEach(key => {
      var td = document.createElement('td');
      // using text content is more secure, since it
      // sanitizes the value and prevents code injections
      td.textContent = row[key];
      tr.appendChild(td);
    });
    table.appendChild(tr);
  });
}

var table = document.getElementById('table');
renderTable(table, dataNew);
<table id="table">
</table>

  • Related