1

I have this array,

[
  {"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"}
]

I want to make it like,

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

This is the array for this representation,

[{"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":""}]

How can I make it using Underscore? I tried to use _.object but I think it is not the solution for this.

JMA
  • 974
  • 3
  • 13
  • 41

2 Answers2

2

You need to loop over the array. Underscore templates use plain old JavaScript, embedded via <% %> tags. Use _.each or Array#forEach to iterate over the array.

user229044
  • 232,980
  • 40
  • 330
  • 338
1

You can use forEach() loop and optional thisArg parameter to create object for each Product and then add time to days with 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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176