首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我想在HTML表之外创建一个JSON对象。我希望最终产品是用来统计来自多个用户的输入

我想在HTML表之外创建一个JSON对象。我希望最终产品是用来统计来自多个用户的输入
EN

Stack Overflow用户
提问于 2018-07-28 03:47:41
回答 2查看 48关注 0票数 -1

这里是一个活跃的学习者,试图弄清楚如何在HTML表之外创建一个JSON对象。我只想要一个特定TD的值,并想给每个值一个递增的数字作为键。我想要一个如下的输出。我的表有一个城市名称的TD,但它没有递增数值的TD,所以我需要用另一种方法添加它。

代码语言:javascript
复制
{
  "mycities" : [
    {
      "Seattle" : "1",
      "Chicago" : "2",
      "New York" : "3"
      "Pitt" : "4",
      "LA" : "5",
      "Fresno" : "6"
    },
  ]
}

下面是我的表的样子:

代码语言:javascript
复制
<table>
    <thead>
        <tr>
            <th>city name</th>
            <th>other city info</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Seattle</td>
            <td>Lots of rain</td>
        </tr>
        etc,etc,etc
    </tbody>
</table>

我试过使用一个替换函数,但在谷歌了很久之后还没有弄明白。如有任何帮助,我们不胜感激!

代码语言:javascript
复制
$(document).ready(function(){   
    $("body").on("click",".submitButtonPri",function(){ 
        count= 1;
        function replacer(key, value) {
          if (typeof value === 'string') {
            return count;
          }
          return value;
        }

        var myRows = [];
        var $headers = $(".rightDash > table thead th");

        var $rows = $(".rightDash > table tbody tr").each(function(index) {
          $cells = $(this).find("td.titlePri");
          myRows[index] = {};
          $cells.each(function(cellIndex) {
            myRows[index][$($cells[cellIndex]).text()] = $(this).text();
          });
          count++;    
        });
        var myObj = {};
        myObj.myrows = myRows;
        console.log(JSON.stringify(myObj,replacer));
    }); 
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-28 03:52:11

使用reduce遍历正文中的tr,并将tr中第一个td的文本内容用作城市名称。提供给reduce的函数的第三个参数表示迭代索引:

代码语言:javascript
复制
const cityData = [...document.querySelectorAll('tbody > tr')]
  .reduce((a, tr, i) => {
    a[tr.children[0].textContent] = i + 1;
    return a;
  }, {});
console.log(
  { mycities: [
    cityData
  ]}
);
代码语言:javascript
复制
<table>
  <thead>
    <tr>
      <th>city name</th>
      <th>other city info</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Seattle</td>
      <td>Lots of rain</td>
    </tr>
    <tr>
      <td>Chicago</td>
      <td>Lots of rain</td>
    </tr>
    <tr>
      <td>New York</td>
      <td>Lots of rain</td>
    </tr>
  </tbody>
</table>

票数 0
EN

Stack Overflow用户

发布于 2018-07-28 04:01:06

您可以从这个简单的脚本开始:

代码语言:javascript
复制
$('td').each(function(index, obj) {console.log(index, $(this).html())});

它返回您需要的所有内容,并且您只需要以任何方式组装JSON

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51564636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档