如何使用 Underscore js 模板将数组转换为 HTML table?

How can I transform an array into a HTML table using Underscore js templating?

我有这个数组,

[
  {"Product":"A","time":"00:21:59","date":"2016-09-05"},
  {"Product":"B","time":"00:11:59","date":"2016-09-07"},
  {"Product":"A","time":"00:11:59","date":"2016-09-08"}
]

我想让它像,

Type | Mon   | Tue | Wed   | Thu   | Fri | Sat | Sun
--------------------------------------------------
A    |0:21:59|     |       |0:11:59|     |     | 
B    |       |     |0:11:59|       |     |     |

这是此表示的数组,

[{"Type":A,"Mon":"0:21:59","Tue":"","Wed":"","Thu":"0:11:59","Fri":"","Sat":"","Sun":""},
{"Type":B,"Mon":"","Tue":"","Wed":"0:11:59","Thu":"","Fri":"","Sat":"","Sun":""}]

如何使用 Underscore 实现? 我尝试使用 _.object 但我认为这不是解决方案。

您需要遍历数组。下划线模板使用普通的旧 JavaScript,通过 <% %> 标签嵌入。使用 _.eachArray#forEach 遍历数组。

您可以使用 forEach() 循环和可选的 thisArg 参数为每​​个产品创建对象,然后使用 Date#getDay()

将时间添加到天数

var data = [
  {"Product":"A","time":"00:21:59","date":"2016-09-05"},
  {"Product":"B","time":"00:11:59","date":"2016-09-07"},
  {"Product":"A","time":"00:11:59","date":"2016-09-08"}
];
var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var result = [];

data.forEach(function(o) {
  var date = new Date(o.date).getDay() - 1;
  if (!this[o.Product]) {
    this[o.Product] = {
      Type: o.Product,
      "Mon": "",
      "Tue": "",
      "Wed": "",
      "Thu": "",
      "Fri": "",
      "Sat": "",
      "Sun": ""
    }
    result.push(this[o.Product])
  }
  this[o.Product][days[date]] = o.time;
}, {})

console.log(result)