istudent Ответов: 1

Как я могу итерации стол ТР и создать JSON-объектов


I have a table from which i would like to iterate over and create json data. 
	I would like to get properties from column head and value from tbody td.
I would like to get myContact = [{Name = "Mary Jane", Gender= "female"},{Name = "Peter Parker", Gender= "male"}]


<pre><table>
<thead>
<tr><td>Name</td><td>Gender</td></tr>
</thead>
<tbody>
<tr><td>Mary Jane</td><td>female</td></tr>
<tr><td>Peter Parker</td><td>Male</td></tr>
</tbody>
</table>


Что я уже пробовал:

Я могу только создать массив объекта массива.

$('#myButton').on('click', function () {
            var table = $('#myTable');
            var data = getTableData(table);
            console.log(data);

            $.ajax({
                url: "/home/DownloadContacts",
                method: "get",
                data: { "list": data , "type":1}
            }).done(function (response) {
                console.log(response.data);
            });
        });

        function getTableData(table) {
            var data = [];
            var target = $('tr').not('thead tr');
            //table.find('tr').each(function (rowIndex, r) {
            target.each(function (rowIndex, r) {
                var cols = [];
                $(this).find('th,td').each(function (colIndex, c) {
                    cols.push(c.textContent);
                });
                data.push(cols);
            });
            return data;
        }

1 Ответов

Рейтинг:
11

littleGreenDude

Это должно дать вам то, что вам нужно:

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function CreateJson() {
	
	var myRows = [];
	var $headers = $("thead tr").find("td"); 
	var $rows = $("tbody tr").each(function(index) {
	  $cells = $(this).find("td");
	  myRows[index] = {};
	  $cells.each(function(cellIndex) {
		myRows[index][$($headers[cellIndex]).html()] = $(this).html();
	  });    
	});

	// Put this an object to convert to JSON
	var myObj = {};
	myObj.myrows = myRows;
	alert(JSON.stringify(myObj));
}

    $().ready(function() {

		$("#btnTableToJson").click(function() {
            CreateJson();
        });
    });
</script>
<style>
</style>
<html>


<body>
<table id="myTable">
<thead>
<tr><td>Name</td><td>Gender</td></tr>
</thead>
<tbody>
<tr><td>Mary Jane</td><td>female</td></tr>
<tr><td>Peter Parker</td><td>Male</td></tr>
</tbody>
</table>
<input id="btnTableToJson" type="button" value="To JSON" />
</body>
</html>