使用Javascript数组和对象创建表

时间:2014-12-28 23:54:00

标签: javascript jquery html-table

我有一个数组和一个对象:

labels = ['ID','Name']; 
object = {
    ["id": "1", 'name': "richard"],
    ["id": "2", 'name': "santos"]
};

我必须创建一个这样的表:

<table>
<thead>
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Richard</td>
        <td>Santos</td>
    </tr>
</tbody>

问题在于:
“对象”变量有时可能有不同的键名,所以我必须动态地用其他对象创建这个表,我试图整天这样做但没有成功,任何人都可以帮助我吗?我是Javascript的新手。 obs:标签和对象变量总是具有相同的大小。

某种物品。

var labels = ['ID','NOME'];
var object = {
    ["id": "1", 'nome': "richard"],
    ["id": "2", 'nome': "adriana"]
};

var labels = ['ID','NAME', 'PLATE'];
var object = {
    ["id": "1", 'nome': "jetta",  'plate': "DFG-1222"],
    ["id": "2", 'nome': "fusion", 'plate': "DFF-3342"]
};

4 个答案:

答案 0 :(得分:3)

最初有两个问题:

  1. 我是N a 我还是N o 我?请修复你的拼写错误(我知道Nome是法语,所以如果它不是拼写错误,我建议你引入i18n解决方案。)
  2. 另外请注意您的语法错误(有些已经提供了您可以考虑的建议编辑)。
  3. 之后,这是我根据输入数据以编程方式创建表的方法:

    &#13;
    &#13;
    function buildTable(labels, objects, container) {
      var table = document.createElement('table');
      var thead = document.createElement('thead');
      var tbody = document.createElement('tbody');
    
      var theadTr = document.createElement('tr');
      for (var i = 0; i < labels.length; i++) {
        var theadTh = document.createElement('th');
        theadTh.innerHTML = labels[i];
        theadTr.appendChild(theadTh);
      }
      thead.appendChild(theadTr);
      table.appendChild(thead);
    
      for (j = 0; j < objects.length; j++) {
        var tbodyTr = document.createElement('tr');
        for (k = 0; k < labels.length; k++) {
          var tbodyTd = document.createElement('td');
          tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
          tbodyTr.appendChild(tbodyTd);
        }
        tbody.appendChild(tbodyTr);
      }
      table.appendChild(tbody);
    
      container.appendChild(table);
    }
    
    var labels1 = ['ID', 'Name']; 
    var objects1 = [
      {"id": "1", 'name': "richard"},
      {"id": "2", 'name': "santos"}
    ];
    
    var labels2 = ['ID', 'NOME'];
    var objects2 = [
      {"id": "1", 'nome': "richard"},
      {"id": "2", 'nome': "adriana"}
    ];
    
    var labels3 = ['ID', 'NAME', 'PLATE'];
    var objects3 = [
      {"id": "1", 'name': "jetta",  'plate': "DFG-1222"},
      {"id": "2", 'name': "fusion", 'plate': "DFF-3342"}
    ];
    
    buildTable(labels1, objects1, document.getElementById('a'));
    buildTable(labels2, objects2, document.getElementById('b'));
    buildTable(labels3, objects3, document.getElementById('c'));
    &#13;
    table {
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid black;
    }
    &#13;
    <div id="a"><p>Table 1</p></div>
    <div id="b"><p>Table 2</p></div>
    <div id="c"><p>Table 3</p></div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

这是我们项目的工作程序。它有三个参数:

htmlTable(selector, data_array [, column_names]);

column_names 参数是可选的:如果省略它,该函数会从第一行创建列名(如果存在)。

它直接在DOM中创建HTML标记,但如果需要,可以重写它以生成HTML作为字符串。请参阅下面的工作代码:

&#13;
&#13;
var labels = ['id','name']; 
var object = [{"id":"1",'name': "richard"},{"id":"2",'name': "santos"}];
htmlTable("#res0",object, labels);

var labels = ['id','nome']; 
var object = [{"id":"1",'nome': "richard"},{"id":"2",'nome': "adriana"}];
htmlTable("#res1",object, labels);

var labels = ['id','name', 'plate']; 
var object = [{"id":"1",'name': "jetta",'plate': "DFG-1222"},
              {"id":"2",'name': "fusion",'plate': "DFF-3342"}];
htmlTable("#res2",object, labels);

// Without labels array
var data3 = [{a:1,c:2},{a:3,c:3}];
htmlTable("#res3",data3);

function htmlTable(selector, data, columns) {
	var sel = document.querySelector(selector);
	if(!sel) {
		throw new Error('Selected HTML element is not found');
	};	

	if((!columns) || columns.length == 0) {
        columns = Object.keys(data[0]);
	}

	var tbe = document.createElement('table');
	var thead = document.createElement('thead');
	tbe.appendChild(thead);

  var tre = document.createElement('tr');
  for(var i=0;i<columns.length;i++){
    var the = document.createElement('th');
    the.textContent = columns[i];
    tre.appendChild(the);
  }
  thead.appendChild(tre);

	var tbody = document.createElement('tbody');
	tbe.appendChild(tbody);
	for(var j=0;j<data.length;j++){
		var tre = document.createElement('tr');
		for(var i=0;i<columns.length;i++){
			var the = document.createElement('td');
			the.textContent = data[j][columns[i]];
			tre.appendChild(the);
		}
		tbody.appendChild(tre);
	};
	emptyDOMChildren(sel);
	sel.appendChild(tbe);
};

// Utility function to fast delete all children of element if it is not empty
// Can be replaced with simple but relatively "slower" container.innerHTML = "";
function emptyDOMChildren (container){
  var len = container.childNodes.length;
  while (len--) {
    container.removeChild(container.lastChild);
  };
};
&#13;
<div id="res0"></div>
<div id="res1"></div>
<div id="res2"></div>
<div id="res3"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

<div id="test"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script   src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
arr1 = [
{"Name":"Peter","RollNo" : 1234,},
{"Name":"John","RollNo" : 1234,},
{"Name":"Kevin","RollNo" : 1234,},
];

$.each(arr1, function(i){
   var templateString = '<table class="table card"><thead> <tr><td><p>My name is: '+arr1[i].Name+'</p><p>My RollNo is: '+arr1[i].RollNo+'</p></td></tr></thead></table>';
$('#test').append(templateString);
})
 </script>

答案 3 :(得分:0)

这是对@ Kaushar * s答案的改进,其中带有带有标题的html表。这是一个没有对象的纯数组的快速可行的解决方案。

ags = [
  ['proj', 'Duales Studium zum Master of Science Wirtschaftsinformatik'],
  ['Kess', 'Systemadministrator Linux'],
  ['foo', 'Customer Success Engineer (EMEA)'],
]

templateString = '<table class=table><tr><th>Firma</th><th>Job</th><th>Status</th><th>Datum</th></tr>'
$.each(ags, function (i) {
  templateString += '<tr><td>' + ags[i][0] + '</td><td>' + ags[i][1] + '</td><td>Status</td><td>Datum</td></tr>'
})
templateString += '</table>'
$('#fa').append(templateString)
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
      <div id="fa"></div>