【问题标题】:How to insert a row in Javascript with a loop?如何使用循环在 Javascript 中插入一行?
【发布时间】:2019-05-30 09:24:38
【问题描述】:

我有一个 json 文件,我想用 Javascript 将数据转换成表格。我发现了一些类似的问题How to convert the following table to JSON with javascript?loop through a json object,但它们都使用 jQuery 并在 html web 上显示表格。我只需要一个简单的循环将行插入表中。我试过'append'、'insert'和'insertRow',都不起作用。谁能给我一个提示?

Json 文件:

{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }

我的代码:

    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]         
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }

编辑:添加预期输出:将 json 文件更改为以下结构。

[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'], 
  ]

【问题讨论】:

  • 您可以随时将 json 转换为普通数组,然后附加您想要的数据,然后将其转换回 json
  • 请解释这部分应该是什么以及它与其余代码的关系如何? "v": json["hits"]["hits"][i]["_source"]...

标签: javascript json


【解决方案1】:

我猜你需要push(或者concat / push(...elements) 如果你想添加行数组)

    jdata.rows = [];
    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]         
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.push(row);
        // for elements from row
        // jdata.rows.push(...row)
    }

【讨论】:

  • 感谢您的帮助。 “推”是个好方法。但我得到错误'无法读取未定义的属性'0''。是不是对数组和json数据理解有误?
  • 那是哪一行?在这段代码中,我只能看到数字索引是json["hits"]["hits"][i]。尝试console.log(json["hits"]) 并检查元素检查器控制台中的值(proly ctrl+shift+i
  • 我尝试了 'console.log(json["hits"]["hits"])',结果是我想要的正确 json。
  • 我发现'无法读取未定义的属性'0''的问题。删除代码中的一个括号:row = [ { "c":...} ] => row = {"c"...}。现在效果很好。再次感谢。
【解决方案2】:

您的代码中有一些错误

  1. JSON 需要是一个数组,以便您可以循环显示每个对象。
  2. insertRow() 是 Table 对象的方法,jdata.rows 不是 Table 对象而是数组。

由于您使用了insertRow(),我已经重写了您的代码以使用表对象方法显示表数据。这是一个代码sn-p

编辑:您可以使用push() 方法来创建所需的JSON 结构。我已经编辑了代码 sn-p 以创建您所需的 JSON。

var jdata = {
  cols: [{
      "id": "1",
      "label": "name",
      "type": "string"
    },
    {
      "id": "2",
      "label": "country",
      "type": "string"
    }
  ],
  rows: []
};

var persons = [{
    "name": "lily",
    "country": "china",
    "age": 23
  },
  {
    "name": "mike",
    "country": "japan",
    "age": 22
  }, {
    "name": "lucy",
    "country": "korea",
    "age": 25
  }
];

var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);

jdata.cols.forEach((col, index) => {
  var cell = rowHeader.insertCell(index);
  cell.innerHTML = col.label;
});

persons.forEach((person, index) => {
  var rowFooter = footer.insertRow(index);
  rowFooter.insertCell(0).innerHTML = person.name;
  rowFooter.insertCell(1).innerHTML = person.country;
  
  jdata.rows.push([person.name, person.country]);
});

console.log(jdata.rows);
<table id="table">

</table>

【讨论】:

  • 感谢您的明确评论!但我不希望表格显示在网络上。我想将 json 文件传输到新结构(已编辑)。
  • @landy 我已编辑我的答案以包含您的新 JSON 结构。
猜你喜欢
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 2013-07-27
  • 2021-07-19
  • 1970-01-01
  • 2015-03-16
相关资源
最近更新 更多