Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我想从HTML表中创建一个JSON对象。我希望最终产品用于统计来自多个用户的输入_Javascript_Json - Fatal编程技术网

Javascript 我想从HTML表中创建一个JSON对象。我希望最终产品用于统计来自多个用户的输入

Javascript 我想从HTML表中创建一个JSON对象。我希望最终产品用于统计来自多个用户的输入,javascript,json,Javascript,Json,这里是一个活跃的学习者,试图找出如何从HTML表中创建JSON对象。我只需要一个特定TD的值,并给每个值一个递增的数字作为键。我想要下面这样的输出。我的表中有一个城市名称的TD,但它没有一个带有递增数值的TD,所以我需要以另一种方式添加它 { "mycities" : [ { "Seattle" : "1", "Chicago" : "2", "New York" : "3" "Pitt" : "4", "LA" : "5"

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

{
  "mycities" : [
    {
      "Seattle" : "1",
      "Chicago" : "2",
      "New York" : "3"
      "Pitt" : "4",
      "LA" : "5",
      "Fresno" : "6"
    },
  ]
}
我的桌子是这样的:

<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>
使用reduce迭代正文中的trs,使用tr中第一个td的文本内容作为城市名称。为reduce提供的函数的第三个参数表示迭代索引:

const cityData=[…document.querySelectorAll'tbody>tr'] .reducea,tr,i=>{ a[tr.children[0].textContent]=i+1; 返回a; }, {}; console.log {我的城市:[ 城市数据 ]} ; 城市名称 其他城市信息 西雅图 雨下得很大 芝加哥 雨下得很大 纽约 雨下得很大
您可以从以下简单脚本开始:

$('td').each(function(index, obj) {console.log(index, $(this).html())});

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

您不能使用的是JSON对象。这正是我想要实现的。谢谢朋友!
$('td').each(function(index, obj) {console.log(index, $(this).html())});