javascript - 使用 JQuery 从表构建 JSON

标签 javascript jquery json

我正在尝试使用可编辑的表在 JQuery 中构建以下 JSON,但我不知道应该从哪里开始,因为我的标题、登机区(列)数和路线序列(行)数发生了变化一直如此,因此我必须手动提取数据并构造每行的 JSON。预先感谢您的任何评论和回复。

{  "name": txtRouteName.val(),
  "serial": [
    { "rsn": "X100", "boardingzone": [
      { "name": "Foo", "time": "8:00" },
      { "name": "Bar", "time": "8:15"}
    ] },
    { "rsn": "X101", "boardingzone": [
      { "name": "Foo", "time": "9:00" },
      { "name": "Bar", "time": "9:15"}
    ] }
  ] 
};    

表格显示如下:

<table id="table1">
   <tr>
   <td>RSN</td>
       <td>Foo</td>
       <td>Bar</td>
   </tr>                        
  <tr>
      <td>X100</td>
      <td>8:00</td>  
      <td>8:15</td>
  </tr>
  <tr>
      <td>X101</td>
      <td>9:00</td>  
      <td>9:15</td>
  </tr>
</table>

最佳答案

首先,我建议您使用 th 作为表格标题:

<table id="table1">

   <tr>
       <th>RSN</th>
       <th>Foo</th>
       <th>Bar</th>
   </tr>

然后你可以:

function parseTable(table) {
    // Helper function to extract the text content of a cell
    function getText(i, cell) { return $(cell).text().trim() };

    // Get the text of the headings as an array
    var headings = $(table).find('tr:eq(0)').find('th').map(getText);

    // Get the text of the values as an array of arrays (values in rows)
    var values = $(table).find('tr:gt(0)').map(function(i, row) {
        return $(row).find('td').map(getText);
    });

    // Map the data according to these rules:
    // One object per row, with `boardingzone` keeping an array of the values
    var result = $.map(values, function(row) {
        var obj = {};
        obj[headings[0]] = row[0];
        obj.boardingzone = $.map(row.slice(1), function(value, i) {
            return {
                name: headings[i + 1],
                time: value
            }
        });
        return obj;
    });

    return result;
}
console.log(JSON.stringify(parseTable("#table1")));

关于javascript - 使用 JQuery 从表构建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340609/

相关文章:

javascript - 在 Meteor 中实现 NASA-TLX

ajax - 在 jQuery 中将 processData 设置为 false 会破坏我的 AJAX 请求

javascript - 我需要什么导入才能使 jQuery 弹出对话框正常工作?

python - 生成数百万个json数据

javascript - 为什么 Root 组件的状态没有改变?

javascript - 如何在不丢失宽高比的情况下使图像填充 90% 的屏幕

java - 使用fasterxml从JSON创建Java对象时出现异常

php - 如何使用主键日期解码json中多行数据并在php表中显示

javascript - 如何计算接近无穷大或 0 的极限?

javascript - 从 Javascript 更新数据库属性