What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object:

let obj = {
 "sessions": [{
      "date": "15-05-2021"
  },
  {
      "date": "16-05-2021"
  },
  {
      "date": "18-05-2021"
  }]
}

The desired output should look like this:

let output = {
 "sessions": [{
      "date": "14-05-2021"
  },
  {
      "date": "15-05-2021"
  },
  {
      "date": "16-05-2021"
  },
  {
      "date": "17-05-2021"
  },
  {
      "date": "18-05-2021"
  },
  {
      "date": "19-05-2021"
  },
  {
      "date": "20-05-2021"
  }]
}

Here is a function that generates an array of dates from today to the next 7 days:

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

getWeekDates();

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

I'm new at this, so please bear with me.

Thanks in advance...

Answer №1

To update the obj.sessions variable with newly generated dates, simply replace it with the following code.

let obj = {
  "sessions": [{
       "date": "15-05-2021"
   },
   {
       "date": "16-05-2021"
   },
   {
       "date": "18-05-2021"
   }]
}

function generateNewDates() {
    let dates = [];
    dates.push({ "date": new Date(Date.now() + 1000 * 3600 * 1).toLocaleDateString('en-GB').replace('/', '-').replace('/', '-')});
    for (let i = 1; i <= 6; i++) {
      dates.push({ "date": new Date(Date.now() + 1000 * 3600 * (i * 24)).toLocaleDateString('en-GB').replace('/', '-').replace('/', '-')});
    }
    obj.sessions = [...dates]
    console.log(obj)
}

generateNewDates();

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

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Simplify typing in TypeScript using default generic parameters

Imagine I came across the following object: const inquiries = { whoCreatesIssues: { options: { sameTeam: { id: 'SAME_TEAM' }, management: { id: 'MANAGEMENT' ...

Having some trouble creating a ping command in discord.js that displays latency; encountered this error message

I encountered an issue while trying to create a ping command that displays latency. I am unsure why this error is showing up, here is the specific error message - TypeError: Cannot read properties of undefined (reading 'ping') at Object.execu ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

Tips for accurately typing a "Type Mapping" function

In my code, I have a specific type designed for a function that takes one type I as input and returns another type O as output. Here is how it currently looks: export interface IFunctionalMapping<I, O, K extends keyof O> { [prop: Extract<O[K], ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

Utilizing Angular 2 for Element Selection and Event Handling

function onLoaded() { var firstColumnBody = document.querySelector(".fix-column > .tbody"), restColumnsBody = document.querySelector(".rest-columns > .tbody"), restColumnsHead = document.querySelector(".rest-columns > .thead"); res ...

Error: Unable to locate module: 'fs' in 'node_modulesdotenvlib' - Next.js

I'm currently incorporating dotenv into my React project to use for API_URL. However, when I attempt to implement it in the index.js file within Next.js, I encounter the following error: Module not found: Can't resolve 'fs' in 'nod ...

Creating a setup in TypeScript to enable imports between CommonJS and ES modules (for node-fetch and Express)

I'm facing a challenge in trying to integrate two libraries into a single project: fetch-node, an ES module, and Express, which follows the CommonJS format. The issue arises from needing to import fetch-node using: import fetch from 'node-fetch&a ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

An error has occurred in Typescript stating that there is no overload that matches the call for AnyStyledComponent since the update to nextjs

Upgraded to the latest version of nextjs, 13.3.1, and encountered an error in the IDE related to a styled component: Received error TS2769 after the upgrade: No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedSty ...

Improving the functionality of a dynamic Mongoose JS application

Hey there, I have a pretty simple question that I couldn't find an answer to on Google. So, I'm experimenting with Mongoose JS and I'm curious about how to update a live application. Let's say I've defined a schema in my node.js ...

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure: <div id="outside-one"> <div class="inside" id="1"></div> <div class="inside" id="2"></div> <div ...

The JQuery datepicker fails to function properly when the input field is modified from read-only

Utilizing the datepicker in conjunction with an MVC3 application. I aim to keep the input field as readonly until triggered by an edit button. Upon focusing on the field, I want the datepicker functionality to be activated. The code snippet below functio ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

Having trouble with Grunt and Autoprefixer integration not functioning properly

Joining a non-profit open source project, I wanted to contribute by helping out, but I'm struggling with Grunt configuration. Despite my research, I can't seem to figure out why it's not working. I am trying to integrate a plugin that allow ...

Stopping the page from scrolling back to the top when an asynchronous update occurs in Angular

Once the asynchronous request is complete, I dynamically add a new element to the top with this code snippet: Array.prototype.unshift.apply(scope.conversation, conversation.data.message); The issue arises when the added element causes the scroll position ...

Maintain original image file name when downloading

I have successfully created a download link containing a base 64 encoded image. The only issue is that I need to retain the original file name, which is dynamic and cannot be hardcoded. downloadImage: function(){ var image_url = document.getEleme ...