0

I want to make json object of html table in javascript.Currently I am able to read the each cells value in javascript, the only problem is that I am not able to retrieve as per my need so think of any suggestion here. Currently getting value like:

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;
    }
}

This is how i am able to read the each cell value.The table format is as follow:

header:      company_1      company_2      company_3

Question1    answer_1       answer_1       answer_1

Question2     answer_2       answer_2       answer_2

and so on.How can i read the value so that i can get object like:

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:""}]}]

Please give some suggestion.

user3406754
  • 69
  • 1
  • 7
  • Hope the below site helps you. http://stackoverflow.com/questions/16507222/create-json-object-dynamically-via-javascript-without-concate-strings – Manjunath D R Aug 11 '14 at 06:32
  • sorry there the situation is that the rows are different. – user3406754 Aug 11 '14 at 06:38
  • you have to transpose the table first http://stackoverflow.com/questions/2730699/convert-td-columns-into-tr-rows [link to JSFIDDLE](http://jsfiddle.net/karthickj25/b76aks69/) – karthickj25 Aug 11 '14 at 06:52
  • as per design concert we cant transpose table but for json object it is ok, so on jsfiddle how to get json object as shown in question. – user3406754 Aug 11 '14 at 07:08

1 Answers1

0

You simply need to change the way you put values to 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);
});
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98