javascript - 使用 Javascript 按月将 JSON 解析为表格

标签 javascript jquery arrays json html-table

我无法将 JSON 对象解析为 html 表。基本上我的 JSON 数据 [EDITED] 看起来像这样:

[  
   {  
      'category': 'Automotive (Motor)',
      'month':8,
      'month_now':'Aug',
      'year':2018,
      'lists':{  
         'total':1,
         'price':591600
      }
   },
   {  
      'category': 'Health',
      'month_now':'Aug',
      'month':8,
      'year':2018,
      'lists':{  
         'total':21,
         'price':14448600
      }
   }
]

我想创建一个这样的表:

我想添加从 Jan 到 Des 的月份,如果每个月都没有总值,则使用空数据。

我已经阅读了很多关于JSON格式的知识,但我的知识非常有限,我需要帮助-__-

我正在尝试,这是我的代码:

$(document).ready(function () {

    var json = [{'category': Automotive (Motor),'month': 8, 'month_now': 'Aug', 'year': 2018, 'lists': {'total': 1, 'price': 591600}}, {'category': Health, 'month_now': 'Aug', 'month': 8, 'year': 2018, 'lists': {'total': 21, 'price': 14448600}}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + json[i].category + "</td>");
        tr.append("<td>" + json[i].month + "</td>");
        tr.append("<td>" + json[i].lists + "</td>");
        $('table').append(tr);
    }
});

这是 html :

<table>
    <tr>
        <th>Category</th>
        <th>Month</th>
        <th>Total</th>
    </tr>
</table>

最佳答案

  1. 您需要用引号将您的类别引起来。
  2. 从列表对象中获取 total 属性

$(document).ready(function() {
  var json = [{
    'category': 'Automotive (Motor)',
    'month': 8,
    'month_now': 'Aug',
    'year': 2018,
    'lists': {
      'total': 1,
      'price': 591600
    }
  }, {
    'category': 'Health',
    'month_now': 'Aug',
    'month': 8,
    'year': 2018,
    'lists': {
      'total': 21,
      'price': 14448600
    }
  }];

  var tr;
  for (var i = 0; i < json.length; i++) {
    tr = $('<tr/>');
    for (var ii = 0; ii < 12; ii++) {
      tr.append($('<td>'));
    }

    tr.find('td:eq(0)').html(json[i].category);
    tr.find('td:eq('+json[i].month+')').html(json[i].lists.total);
    
    $('table').append(tr);
  }
});
table {
  width: 100%;
  text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Unit</th>
    <th>J</th>
    <th>F</th>
    <th>M</th>
    <th>A</th>
    <th>M</th>
    <th>J</th>
    <th>J</th>
    <th>A</th>
    <th>S</th>
    <th>O</th>
    <th>N</th>
    <th>D</th>
  </tr>
</table>

关于javascript - 使用 Javascript 按月将 JSON 解析为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52143127/

相关文章:

java - 为什么 hasNextInt() 在这里返回 false ?

javascript - 如何从捆绑文件中导入命名的 SystemJS 模块?

jquery - 自定义 Jquery "Lightbox"不工作

javascript - 如何在单击按钮时切换两个不同输入的文本?

javascript - 从键盘输入一个单词并将每个字母存储到一系列多个输入文本框中

java - Java while 循环中如何将数组合并为一个数组

javascript - 满足条件时计数错误

javascript - 了解代码片段中的条件运算符和条件赋值

javascript - 如何在 Javascript 中将对象的字段名称转换为值

javascript - 单击复选框+按钮后动态更改 slider 值