遍历表并将值存储为键/值对

时间:2018-12-10 13:34:25

标签: javascript jquery

我有一个类似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);

        });

我们非常感谢您的帮助。谢谢

2 个答案:

答案 0 :(得分:3)

您的代码有很多问题:

  1. myArray是在循环内定义的,因此您始终使用空数组实例化它。

  2. 选择器不起作用,因为您正在遍历每个元素。

  3. asset_keyasset_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>

答案 1 :(得分:0)

您可以选择所有元素并对其进行循环,而不必遍历各行并查找每个td。

var ids = $('.asset-id')
var vals = $('.asset-val')

var result = [];
ids.each(function(i, v){
  result.push({ id: +v.textContent, value: +vals.eq(i).text()})
  // result.push({ id: +ids.eq(i).text(), value: +vals.eq(i).text()})
  
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
    </tbody>
    </table>