首页 > 解决方案 > 从表数据中获取 Javascript 对象数组

问题描述

我可能是 javascript 新手,我想以 json 对象格式从表中提取数据我有一个看起来像这样的表

<table>
<thead>
<tr>
<th class="active">Bolumn</th>
<th class="active">Column</th>
<th class="active">Dolumn</th>
<th>Molumn</th>
</tr>
</thead>
<tbody>
<tr>
<td class="active">Bolumn Data</td>
<td class="active">Column Data</td>
<td class="active">Dolumn Data</td>
<td>Molumn Data</td>
</tr>
<tr>
<td class="active">Bolumn Data 1</td>
<td class="active">Column Data 1</td>
<td class="active">Dolumn Data 1</td>
 <td>Molumn Data 1</td>
</tr>
<tr>
<td class="active">Bolumn Data 2</td>
<td class="active">Column Data 2</td>
<td class="active">Dolumn Data 2</td>
<td>Molumn Data 2</td>
</tr>
</tbody>
</table>    

在表中有些有活动课程,我只想要这个活动课程数据

所以我想要 json 格式看起来像这样,我想要在 jquery 方法中

[{"Bolumn":"Bolumn Data","Column":"Column Data","Dolumn":"Dolumn Data"},
{"Bolumn":"Bolumn Data 1","Column":"Column Data 1","Dolumn":"Dolumn Data 1"},
{"Bolumn":"Bolumn Data 2","Column":"Column Data 2","Dolumn":"Dolumn Data 2"}]

提前致谢

更新:我试过这样的代码,但我不知道如何实现这一点

var array = [];
$('tr').each(function (i) {
    $(this).find('td').each(function (i) {
        if ($(this).hasClass('active')) {
            array.push($(this).text());
        }
    });
});

标签: javascriptjqueryhtml

解决方案


您的代码非常接近工作。然而,它需要一些东西来获得你想要的结果。首先,由于您需要对象,因此您需要在标题中找到的键。您可以像处理数据一样创建一个数组:

var headers = []
$('tr th').each(function (i) {
    headers.push($(this).text())
})

现在,您可以在循环中按索引引用标题,并随时为键分配值:

// find headers
var headers = []
$('tr th').each(function(i) {
  headers.push($(this).text())
})
// result array
var array = [];
$('tr').each(function(i) {
  // declare object variable but dont set it's value
  // unless there are objects to find
  var rowObj
  $(this).find('td').each(function(i) {
    if (!rowObj) rowObj = {}
    if ($(this).hasClass('active')) {
      // use the header we found earlier
      rowObj[headers[i]] = $(this).text()
    }
  });
  // if we found active objects, rowObje will be defined
  if (rowObj) array.push(rowObj)
});
console.log(array)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th class="active">Bolumn</th>
      <th class="active">Column</th>
      <th class="active">Dolumn</th>
      <th>Molumn</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="active">Bolumn Data</td>
      <td class="active">Column Data</td>
      <td class="active">Dolumn Data</td>
      <td>Molumn Data</td>
    </tr>
    <tr>
      <td class="active">Bolumn Data 1</td>
      <td class="active">Column Data 1</td>
      <td class="active">Dolumn Data 1</td>
      <td>Molumn Data 1</td>
    </tr>
    <tr>
      <td class="active">Bolumn Data 2</td>
      <td class="active">Column Data 2</td>
      <td class="active">Dolumn Data 2</td>
      <td>Molumn Data 2</td>
    </tr>
  </tbody>
</table>


推荐阅读