2 回答
TA贡献1862条经验 获得超6个赞
您可以获取td索引,并根据此获取 该索引处的值,并将相同的值推送到JSON 数组$headers内。我已经使用(更少),因为只有 4 个标头值,如果您需要所有 tds 值,您可以删除它:lt
演示代码:
$(document).ready(function() {
$("#getJsondata").click(function() {
var jsonData1 = [];
var $headers = ["ID", "ABC", "XYZ", "Test"];
$("#firstTable").find("tbody tr").each(function(index) {
var values = {}; //create obj
//loop through tr > td only < 4
$(this).find("td:lt(4)").each(function(index) {
values[$headers[index]] = $(this).text(); //add values
})
jsonData1.push(values) //push in array
});
alert(JSON.stringify(jsonData1));
});
});
td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="multipleData" style="border:1px solid black;" id="firstTable">
<thead style="background:grey;">
<tr>
<th>Header1</th>
<th>Header2</th>
<th>Header3</th>
<th>Header4</th>
<th>Header5</th>
<th>Header6</th>
</tr>
</thead>
<tbody>
<tr style="border:1px solid black">
<td>22222</td>
<td>test5</td>
<td>3000</td>
<td>abc</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>3333</td>
<td>test1</td>
<td>1000</td>
<td>erf</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>44444</td>
<td>test2</td>
<td>2000</td>
<td>sde</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>55555</td>
<td>test3</td>
<td>3000</td>
<td>fre</td>
<td>22222</td>
<td>Y</td>
</tr>
</tbody>
</table>
<button id="getJsondata" type="button">
GetJsonData
</button>
TA贡献2037条经验 获得超6个赞
这似乎做你想做的
const headers = ["ID", "ABC", "XYZ", "Test"];
$(function() {
$("#getJsondata").on("click", function() {
const data = [];
$("#firstTable").find("tbody tr").each(function() {
data.push({})
$(this).find("td").map(function(i) {
return this.textContent;
}).get() // get the array of all cell contents
.slice(0, -2) // get rid of the last two
.forEach((text,i) => data[data.length-1][headers[i]] = text) // add to the object
})
console.log(JSON.stringify(data));
});
});
td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="multipleData" style="border:1px solid black;" id="firstTable">
<thead style="background:grey;">
<tr>
<th>Header1</th>
<th>Header2</th>
<th>Header3</th>
<th>Header4</th>
<th>Header5</th>
<th>Header6</th>
</tr>
</thead>
<tbody>
<tr style="border:1px solid black">
<td>22222</td>
<td>test5</td>
<td>3000</td>
<td>abc</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>3333</td>
<td>test1</td>
<td>1000</td>
<td>erf</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>44444</td>
<td>test2</td>
<td>2000</td>
<td>sde</td>
<td>22222</td>
<td>Y</td>
</tr>
<tr style="border:1px solid black">
<td>55555</td>
<td>test3</td>
<td>3000</td>
<td>fre</td>
<td>22222</td>
<td>Y</td>
</tr>
</tbody>
</table>
<button id="getJsondata" type="button">
GetJsonData
</button>
添加回答
举报