我有一个带对象的数组(日期和值),问题是该数组中缺少几个日期对象。我希望在每个日期基于开始日期和结束日期完全填充该数组,我们也应该考虑内部日期,因此如果一天之后不存在日期,那么应该在那之后添加当天对象,其值为null。
我为此创建了一个stackblitz:https://stackblitz.com/edit/js-pfbcxz在该代码中,我添加了不同的日期对象以及具有不同时间的相同日期对象。我写了一些代码,但这并没有满足我的要求。只插入少量对象。
另一个解决方案使用moment.js,但我将为我的解决方案编写的内容使用纯粹的Vanilla JavaScript。基本上,我们将使用while循环遍历数组,然后检查当前索引的日期和上一个索引的日期之间是否存在任何差异。如果存在差异,我们将在中间添加日期,并在y上添加空值。
const json_data = [{
x: "2018-06-21T20:30:00Z",
y: 6.39
},
{
x: "2018-07-21T10:30:00Z",
y: 6.39
},
{
x: "2018-07-21T09:30:00Z",
y: 6.39
},
{
x: "2018-08-21T21:30:00Z",
y: 5.93
},
{
x: "2018-09-21T21:30:00Z",
y: 5.93
}
];
const getDates = (startDate, stopDate) => {
const dateArray = [];
let counterDate = startDate;
const stopCounter = new Date(stopDate.setDate(stopDate.getDate() -1));
while (counterDate < stopCounter) {
dateArray.push(counterDate);
counterDate = new Date(counterDate.setDate(counterDate.getDate() + 1));
}
return dateArray;
}
//console.log(getDates(new Date(json_data[0].x),new Date(json_data[1].x)))
let k = 1;
const result = [];
while (k < json_data.length) {
const inBetween = getDates(new Date(json_data[k - 1].x),new Date(json_data[k].x)).map(date => ({
x: date.toISOString(),
y: null
}));
//console.log(inBetween)
if (inBetween.length > 0) {
result.push(json_data[k-1], ...inBetween)
}
if (k === json_data.length - 1) {
result.push(json_data[k]);
}
k++;
}
console.log(result)
尝试将对象列表转换为简单对象
然后搜索对象中的键(日期)。
如果未找到,则使用null创建密钥
var json_data = [
{x: "2018-06-21T20:30:00.000Z", y: 6.39},
{x: "2018-07-21T10:30:00.000Z", y: 6.39},
{x: "2018-07-21T09:30:00.000Z", y: 6.39},
{x: "2018-08-21T21:30:00.000Z", y: 5.93},
{x: "2018-09-21T21:30:00.000Z", y: 5.93}
];
var obj = json_data.reduce((acc, data) => {
acc[data.x] = data.y;
return acc;
}, {});
var firstDate = new Date(json_data[0].x);
var secondDate = new Date(json_data[json_data.length-1].x);
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.round(Math.abs((firstDate.getTime() -
secondDate.getTime())/(oneDay)));
let k=0;
while(k < diffDays) {
let nextDay = new Date(new Date(firstDate).getTime() + (k * oneDay));
if(obj[nextDay] === undefined) {
obj[nextDay.toISOString()] = null
}
k++
}
var res = Object.entries(obj).map(item => ({
x: item[0],
y: item[1],
}));
console.log(res);
您可以使用moment.js库来执行任何类型的日期操作。
Check a date is same or before another date
这是使用moment.js的解决方案
var json_data = [
{ x: "2018-06-21T20:30:00Z", y: 6.39 },
{ x: "2018-07-21T10:30:00Z", y: 6.39 },
{ x: "2018-07-21T09:30:00Z", y: 6.39 },
{ x: "2018-08-21T21:30:00Z", y: 5.93 },
{ x: "2018-09-21T21:30:00Z", y: 5.93 }
];
var obj = json_data.reduce((acc, data) => {
acc[data.x] = data.y;
return acc;
}, {});
var start = moment("2018-06-21T20:30:00Z");
var end = moment("2018-09-21T21:30:00Z");
while (start.isSameOrBefore(end)) {
if (obj[start] === undefined) {
obj[start] = null;
}
start = start.add(1, "days");
}
var res = Object.entries(obj).map(item => ({
x: item[0],
y: item[1],
}));
console.log(JSON.stringify(res))