我有一个像这样的 html 表格
<table>
<tbody><tr><th>Course Name</th>
<th>Course ID</th>
<th>Value</th>
</tr><tr>
<td>Course A</td>
<td class="asset-id">1616781</td>
<td class="asset-val">1306886</td>
</tr>
<tr>
<td>Course B</td>
<td class="asset-id">723507</td>
<td class="asset-val">1306886</td>
</tr>
<tr>
<td>Course C</td>
<td class="asset-id">723503</td>
<td class="asset-val">1306886</td>
</tr>
我想遍历这个表并创建一个对象数组,例如
[{
"id": 1616781,
"value": 1306886
}, {
"id": 723507,
"value": 1306886
}, {
"id": 723503,
"value": 1306886
}]
到目前为止我已经尝试过类似的方法,但它不起作用......
var myArray = [];
$('.asset-id, .asset-val').each(function(i, obj) {
var tmpObj = {};
var asset_key='';
var asset_text='';
tmpObj[asset_key] = $(".asset-id", this).text();
tmpObj[asset_text] = $(".asset-val", this).text();
myArray.push(tmpObj)
console.log(myArray);
});
非常感谢任何帮助。谢谢
最佳答案
您的代码有很多问题:
myArray
是在循环内定义的,因此您始终使用空数组实例化它。选择器不起作用,因为您要循环遍历每个元素。
asset_key
和asset_text
都是空字符串。
以下内容应该适合您:
var arr = [ ];
$('.asset-id').each(function() {
arr.push({
'id': $(this).text(),
'value': $(this).siblings(".asset-val").text()
});
});
console.log( arr );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Course Name</th>
<th>Course ID</th>
<th>Value</th>
</tr>
<tr>
<td>Course A</td>
<td class="asset-id">1616781</td>
<td class="asset-val">1306886</td>
</tr>
<tr>
<td>Course B</td>
<td class="asset-id">723507</td>
<td class="asset-val">1306886</td>
</tr>
<tr>
<td>Course C</td>
<td class="asset-id">723503</td>
<td class="asset-val">1306886</td>
</tr>
</table>
关于javascript - 遍历表并将值存储为键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706803/