Skip to content
Advertisement

How to fill missing dates inside array of object using javascript?

I want to fill this object from today’s date to next 7 days. Here is my object

let obj = {
  "sessions": [{
       "id": 0,
       "available_capacity": 3,
       "date": "15-05-2021"
   },
   {
       "id": 1,
       "available_capacity": 5,
       "date": "16-05-2021"
   },
   {
       "id": 2,
       "available_capacity": 2,
       "date": "18-05-2021"
   }]
}

Expected output:

let output = {
  "sessions": [{
       "date": "14-05-2021"
   },
   {
       "id": 0,
       "available_capacity": 3,
       "date": "15-05-2021"
   },
   {
       "id": 1,
       "available_capacity": 5,
       "date": "16-05-2021"
   },
   {
       "date": "17-05-2021"
   },
   {
       "id": 2,
       "available_capacity": 2,
       "date": "18-05-2021"
   },
   {
       "date": "19-05-2021"
   },
   {
       "date": "20-05-2021"
   }]
}

Here is the code to generate array of dates from today to next 7 days

function getWeekDates() {
    let dates = [];
    for (let i = 0; i <= 6; i++) {
      dates.push(new Date(Date.now() + 1000 * 3600 * (i * 24)).toLocaleDateString('en-GB').replace('/', '-').replace('/', '-'));
    }
    console.log(dates);
}

getWeekDates();

//result: ["14-05-2021", "15-05-2021", "16-05-2021", "17-05-2021", "18-05-2021", "19-05-2021", "20-05-2021"]

How can I fill in the missing dates?

Answer

You can use this code to generate the dates array. You can pass the startDate and numberOfDays you need. In your case you can just dateRange(new Date(), 7)

const DAY_IN_MS = 24 * 60 * 60 * 1000
const dateRange = (startDate, numOfDays) => {
    const startDateInMs = startDate.getTime()
    return [...Array(numOfDays).keys()].map(i => new Date(startDateInMs + i * DAY_IN_MS).toISOString().slice(0,10))
}

let dates = dateRange(new Date(),7);
console.log(dates);

You can use Array.prototype.map and return the check if date exists in obj.sessions using Array.prototype.find then return the object otherwise just return the same date. Array.prototype.find returns undefined if item doesn’t exist.

let obj = {
  "sessions": [{
       "id": 0,
       "available_capacity": 3,
       "date": "15-05-2021"
   },
   {
       "id": 1,
       "available_capacity": 5,
       "date": "16-05-2021"
   },
   {
       "id": 2,
       "available_capacity": 2,
       "date": "18-05-2021"
   }]
}
function getWeekDates() {
    let dates = [];
    for (let i = 0; i <= 6; i++) {
      dates.push(new Date(Date.now() + 1000 * 3600 * (i * 24)).toLocaleDateString('en-GB').replace('/', '-').replace('/', '-'));
    }
    return dates;
}

let dates = getWeekDates();
let r = dates.map(d => {
  let o = obj.sessions.find(x => x.date === d);
  return o ?? {date: d}
 });
console.log(r);
Advertisement