Try converting the list of objects to a simple object
and then search the key (date) in the object.
If not found create the key with 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);
You can use moment.js library to do any kind of date operation.
Add days to date
Check a date is same or before another date
Here is the solution using 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))
yproperty?