【问题标题】:Getting data from JSON and formatting this into a table从 JSON 获取数据并将其格式化为表格
【发布时间】:2021-11-08 08:20:15
【问题描述】:

我对这个有点卡住了。我正在尝试在我的网站上使用 javascript 将我的 API JSON 数据转换为表格。如果不在 JSON 中的数据数组中使用数组,它可以正常工作,每个项目都在新行上,但是一旦我在那里使用嵌套的数据数组,它就会在一行上包含所有数据,用逗号分隔。认为 for 循环可以在这里工作,但我不能 100% 确定这是否是最好的方法。 我已经尝试了多次在线搜索并在自己周围进行了测试,但我似乎无法让它发挥作用。

以下是我正在使用的 JSON 数据的简单版本:

MACLIST = ["ABC","DEF"]
IPLIST = ["10.10.10.10","20.20.20.20"]
ZONELIST = ["Inside","Outside"]

var json = [{"MAC":MACLIST,"IP":IPLIST,"ZONE":ZONELIST},{"SOMETHING ELSE":"OK"}];

使用的脚本:

$(document).ready(function () {
    ko.applyBindings({
        teams: json
    });
});

使用的 HTML:

    <table>
    <thead>
        <tr>
            <th>Device</th>
            <th>IP</th>
            <th>Zone</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: teams">
        <tr>
            <td data-bind="text: MAC"></td>
            <td data-bind="text: IP"></td>
            <td data-bind="text: ZONE"></td>
        </tr>
    </tbody>
</table>

工作 JSON 版本(没有嵌套数组数据)有效:

var json = [{"MAC":"ABC","IP":"10.10.10.10","ZONE":"Inside"},{"MAC":"DEF","IP":"20.20.20.20","ZONE":"Outside}];

任何提示或建议将不胜感激

测试网址JSFiddle Link

【问题讨论】:

    标签: javascript html arrays json knockout.js


    【解决方案1】:

    您可以映射每一行来为每一行创建一个 html 字符串。然后在每一行内,映射每一列,为每个单元格创建 html 字符串。

    var json = [{
      "MAC": "ABC",
      "IP": "10.10.10.10",
      "ZONE": "Inside"
    }, {
      "MAC": "DEF",
      "IP": "20.20.20.20",
      "ZONE": "Outside"
    }];
    
    const makeCell = (content) => {
      return `<td>${content}</td>`
    }
    
    const makeRow = (content) => {
      return `<tr>${content}</tr>`
    }
    
    
    const table = document.querySelector('.table')
    const colHeaders = Object.keys(json[0]).map(key => makeCell(key)).join('')
    const bodyRows = json.map(row => {
      return makeRow(Object.keys(row).map(col => makeCell(row[col])).join(''))
    }).join('')
    
    
    document.querySelector('thead tr').innerHTML = colHeaders
    document.querySelector('tbody').innerHTML = bodyRows
    <table>
      <thead>
        <tr></tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    【讨论】:

    • 感谢您的快速回复。在使用我在 previoius 方法中提到的 JSON 代码之前,我设法让它工作,但我的问题是,所有 JSON 数据都需要在它自己的数组组中,例如 { TABLE DATA },{ OTHER DATA NON TABLE RELATED}。每个表格元素也将位于它们自己的组中,例如 MACLIST = ["ABC","DEF"] / IPLIST = ["10.10.10.10","20.20.20.20"] / ZONELIST = ["Inside","外"]
    【解决方案2】: