Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current 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"
   }]
}

Desired 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"
   }]
}

Below is a function that generates an array of dates for the coming week:

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 add the missing dates to my object?

Answer №1

If you need to create an array of dates, you can utilize the following code snippet. Provide a startDate and the number of days you want in the array. For example, simply use 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);

To check if a certain date exists in obj.sessions, you can make use of Array.prototype.map and utilize Array.prototype.find. If the date is found, return the object; otherwise, return the same date. Array.prototype.find will return undefined if the item is not found.

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);

Answer №2

If you're searching for something similar to the following:


function retrieveWeekDates() {
    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
}
retrieveWeekDates().map(date => {
    return obj.sessions.find(s => s.date === date) || date
})


/* 

Results

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

Removing characters from strings with the use of arrays and iterations

Looking for a way to extract only the numbers from cells filled with a mix of numbers, letters, and symbols like "TS-403" or "TSM-7600". The goal is to remove all non-integer characters and retain only the numerical values like "403". Two possible approac ...

Right-click context menu not working properly with Internet Explorer

Seeking assistance with extracting the URL and title of a website using JavaScript. The script is stored in a .HTM file accessed through the registry editor at file://C:\Users\lala\script.htm Below is the script: <script type="text/java ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Managing JavaScript expiration time in API responses

Seeking help with a JavaScript API I'm new to. The response I received contains a timestamp, which seems like it's in milliseconds. I want to format this time for a countdown but I'm not sure what these milliseconds are referring to. I know ...

Receiving an error stating that .startsWith() is not a function in react native

I'm having trouble searching for items using a search bar. The original items are in 'prod', but I keep encountering errors such as 'startsWith() is not a function' and sometimes '.toLowerCase() is not a function'. const ...

Measuring Load Time Percentage in AngularJS Using $http Requests

I am currently utilizing Angular with my Rails application. I have a sample app and I am interested in displaying the response time required to load a response in Angular. For example, When loading a response of an array containing 100,000 elements, I w ...

Angular Square Grid Design

Attempting to create a square grid layout using CSS for ng-repeat items. Essentially, I am looking to have one big square followed by four smaller squares that combined have the same width and height as the big square. Here is my CSS: .container{ widt ...

What steps should be taken to refresh an Expo app block once new data is retrieved from the database

I'm facing an issue with connecting my expo app to a database. I have utilized react redux to fetch data from the database, and upon successful retrieval of data, I aim to update my furniture block with the obtained information. However, despite recei ...

The concept of selective importing within JavaScript

Seeking guidance on configuring conditional imports for a native library that is built for both node and electron. The challenge arises when one project requires the node implementation for testing, while another project needs the electron version. Projec ...

Sending a variable from JavaScript to an external PHP file

There are numerous questions on similar topics, but I'm struggling to figure it out, my apologies. I have a file containing some JavaScript variables that depend on user input (without using a form) and a normal HTML link to my PHP file. <script& ...

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

NPM is alerting about missing "Repository Field" even though I don't have a repository specified

When experimenting with node.js on my personal projects at home, I encountered the issue of receiving a No Repository Field warning whenever I ran npm install. This dilemma has been discussed in detail in a different topic on Stack Overflow. The documenta ...

Is there a way to retrieve column names from a cursor within a Python Flask application?

Currently, I am in the process of developing an API using Python 3 with Flask and attempting to insert data into MySQL. However, when I receive a response, only the values are returned and I am unable to display them properly in the JSON output for my appl ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

NPM is currently malfunctioning and displaying the following error message: npm ERR! 404

When running npm update -g, the following error occurs: npm ERR! code E404 npm ERR! 404 Not found : default-html-example npm ERR! 404 npm ERR! 404 'default-html-example' is not in the npm registry. npm ERR! 404 You should bug the author to publi ...

When an image is clicked, add the coordinates to a div

Is it possible to append the coordinates displayed when hovering over an image in a div using jQuery? You can see what I have so far in this fiddle: Fiddle Here is the jQuery code: $('.hover').mousemove(function(e){ var hovertext = ...

Data sent as FormData will be received as arrays separated by commas

When constructing form data, I compile arrays and use POST to send it. Here's the code snippet: let fd = new FormData(); for (section in this.data.choices) { let key = section+(this.data.choices[section] instanceof Array ? '[]' : '& ...