1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| (function () { "use strict"; var data = [ { "id": 1, "date": "2018-01-01", "value": 10 }, { "id": 2, "date": "2018-01-02", "value": 1000 }, { "id": 10, "date": "2018-01-08", "value": 101 }, { "id": 2, "date": "2018-01-20", "value": 13 }, { "id": 3, "date": "2018-01-30", "value": 20 } ];
function builder(data, st, et, column = "date", step = 86400000, callback) { var index = 0, result = {}, dataLength = data.length, start = (new Date(st)).getTime(), end = (new Date(et)).getTime();
if (typeof callback == "undefined") { callback = function (dateObject) { var day = dateObject.getDate(), month = dateObject.getMonth() + 1; day = day < 10 ? "0" + day : day; month = month < 10 ? "0" + month : month; return dateObject.getFullYear() + "-" + month + "-" + day; } }
while (start <= end) { for (; index < dataLength;) { var item = data[index], current = (new Date(item[column])).getTime(); if (current == start) { index += 1; if (index >= dataLength) { index = dataLength - 1; } for (var key in item) { result[key] = result[key] || []; if (key == column) { result[key].push(callback(new Date(start))); continue; } result[key].push(item[key]) } break; } for (var key in item) { result[key] = result[key] || []; if (key == column) { result[key].push(callback(new Date(start))); continue; } switch (typeof item[key]) { case "string": result[key].push(""); break; default: result[key].push(0); break; } } break; } start += step } return result; } var result = builder(data, "2018-01-01", "2018-02-03", 'date', 86400000, function (dateObject) { var day = dateObject.getDate(), month = dateObject.getMonth() + 1; day = day < 10 ? "0" + day : day; month = month < 10 ? "0" + month : month; return dateObject.getFullYear() + "/" + month + "/" + day; }); console.log(result);
})();
|