我想在javascript中制作html表的json对象。目前我能够读取javascript中的每个单元格值,唯一的问题是我无法按照我的需要进行检索,所以想一想这里的任何建议。目前获得的价值如下:
var x = document.getElementById("tableId");
for (var i = 0; i < x.rows.length; i++) {
for (var j = 0; j < x.rows[i].cells.length; j++){
tableJsonDTO[name] = x.rows[i].cells[j].innerHTML;
}
}
这是我能够读取每个单元格值的方式。表格格式如下:
header: company_1 company_2 company_3
Question1 answer_1 answer_1 answer_1
Question2 answer_2 answer_2 answer_2
等等。如何读取值,以便我可以获得如下对象:
var obj = [{spname:"company_1",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_2",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_3",qalist:[{question:"",answer:""},{question:"",answer:""}]}]
请提出一些建议。
答案 0 :(得分:0)
您只需更改将值放入tableJsonDTO
的方式即可。 Demo
document.getElementById('toJSON').addEventListener('click', function(){
var table = document.getElementById('mytable'),
names = [].slice.call(table.rows[0].cells),
values = [].slice.call(table.rows, 1),
out = {};
values.forEach(function(row) { //iterate over values
var cells = row.cells,
caption = cells[0].innerHTML; //get property name
[].forEach.call(cells, function(cell, idx) { //iterate over answers
var value = {},
arr;
if(!idx) return; //ignore first column
value[caption] = cell.innerHTML; //prepare value
//get or init array of values for each name
arr = out[names[idx].innerHTML] || (out[names[idx].innerHTML] = []);
arr.push(value);
});
});
console.log(out);
});