简体   繁体   中英

Inserting table <td> cell under a particular header <th> from an Object

Given a Javscript Object:

var obj = {
  "results": [{
      "B": "Row 1 Col 2"
    }, {
      "A": "Row 2 Col 1"
      "B": "Row 2 Col 2"
    }, {
      "C": "Row 3 Coll 3"
    }
  }]

I wish to convert it to a table that looks like the following.

<table border="1">
  <thead>
    <tr>
      <th id="A">A</th>
      <th id="B">B</th>
      <th id="C">C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>Row 1 Col 2</td>
      <td></td>
    </tr>
    <tr>
      <td>Row 2 Col 1</td>
      <td>Row 2 Col 2</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td>Row 3 Col 3</td>
    </tr>
  </tbody>
</table>

Which looks like:

在此处输入图片说明

More precisely, I'm looking for a way to somehow insert the value of a property directly below it. And creating a new header as when a new property emerges while successively reading the object. This is a better way of approaching the problem I feel, as it is more versatile for an arbitrary object.

This is why I was wondering if there was any HTML tag or jQuery way such that I can directly insert a cell under a particular header of my choice instead of calculating and inserting appropriate number of " <td></td> " till I get to the right cell.

Fiddle: https://jsfiddle.net/kqsozme5/2/

Following doesn't care how many columns there are, and works on totally arbitrary object config.

It sorts the column names prior to looping through data again to build rows and creates empty cells as necessary

// create array of column keys and sort
var cols = obj.results.reduce(function(arr, currObj) {
    return arr.concat(Object.keys(currObj).filter(function(key) {
        return arr.indexOf(key) == -1
    }));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';

var rows = obj.results.map(function(item) {
    // loop over column keys checking matches to item keys
    return '<tr>' +
        cols.map(function(key) {
            return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
        }).join('') + '</tr>';
}).join('');
var table = '<table  border="1">' + header + rows + '</table>';

 var obj = { "results": [{ "B": "Row 1 Col 2" }, { "A": "Row 2 Col 1", "B": "Row 2 Col 2" }, { "C": "Row 3 Coll 3" }] }; // create array of column keys and sort var cols = obj.results.reduce(function(arr, currObj) { return arr.concat(Object.keys(currObj).filter(function(key) { return arr.indexOf(key) == -1 })); }, []).sort(); // create header from sorted column keys var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>'; var rows = obj.results.map(function(item) { // loop over column keys checking matches to item keys return '<tr>' + cols.map(function(key) { return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>'; }).join('') + '</tr>'; }).join(''); var table = '<table border="1">' + header + rows + '</table>'; $('body').append(table); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Html:

<tbody id = "idTBody">

Jquery:

for(var result in obj.results)
{
    for(var col in obj.results[result])
    {
        $("#idTBody").append("<tr>");
        if(col == 'A'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
        else {$("#idTBody").append("<td></td>");}
        if(col == 'B'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
        else {$("#idTBody").append("<td></td>");}
        if(col == 'C'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
        else {$("#idTBody").append("<td></td>");}
        $("#idTBody").append("</tr>");
    }
}

why don't use arrays

var object = {
  result: [['a', 'b', 'c'],
           ['', 'rows1 col2', ''],
           ['row2 col1', 'row2 col2', '']]
}

it's easy to convert to tables.

Assuming Your Object is :

var obj = {
"results": [{
  "A": "",
  "B": "Row 1 Col 2",
  "C": ""
}, {
  "A": "Row 2 Col 1",
  "B": "Row 2 Col 2",
  "C": ""
}, {
  "A": "",
  "B": "",
  "C": "Row 3 Coll 3"
}
}]

HTML Would Be:

<table id="trialTable" border="1">
 <thead>
  <tr>
   <th id="A">A</th>
   <th id="B">B</th>
   <th id="C">C</th>
  </tr>
 </thead>
 <tbody>

 </tbody>
 </table>

JQuery will Be:

var tbody = $("#trialTable > tbody");
tbody.empty();
$.each(obj.results, function(index, data) {
  var tr = $("<tr>");
  var td = $("<td>");

  tr.append($('<td>', {
        text: data.A
  }));
  tr.append($('<td>', {
        text: data.B
  }));
  tr.append($('<td>', {
        text: data.C
  }));
  tbody.append(tr);


});

you will get your expected output.As far as i know, using jQuery instead of simple javascript is always easy and less confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM