JavaScript: Transform the content within an array into a set of two dates

In my calendar, the structure is as follows:

const calendar = [{
  "Title": "Go Shopping",
  "dates": [ 
  {
  "DateBeginn": "19.02.2021",
  "DateEnd": "22.02.2021",
  "Where": "Supermarket",
  },
  {
  "DateBeginn": "23.02.2021",
  "DateEnd": "23.02.2021",
  "Where": "Biomarket"
  }]
  }]
  
 const calendarData = calendar.map(main => main.dates.map(d => ({
  Title: main.Title,
  DateBeginn: d.DateBeginn,
  DateEnd: d.DateEnd,
  Where: d.Where,
  
 }))).flat()
  console.log(calendarData)

The output of this code snippet looks like this:

  [
      {
        "Title": "Go Shopping",
        "DateBeginn": "19.02.2021",
        "DateEnd": "22.02.2021",
        "Where": "Supermarket"
      },
      {
        "Title": "Go Shopping",
        "DateBeginn": "23.02.2021",
        "DateEnd": "23.02.2021",
        "Where": "Biomarket"
      }
    ]

Now, my goal is to expand this data into a detailed schedule:

[
  {
    "Title": "Go Shopping",
    "DateBeginn": "19.02.2021",
    "DateEnd": "22.02.2021",
    "Where": "Supermarket"
  },
  {
    "Title": "Go Shopping",
    "DateBeginn": "20.02.2021",
    "DateEnd": "22.02.2021",
    "Where": "Supermarket"
  },
  {
    "Title": "Go Shopping",
    "DateBeginn": "21.02.2021",
    "DateEnd": "22.02.2021",
    "Where": "Supermarket"
  },
  {
    "Title": "Go Shopping",
    "DateBeginn": "22.02.2021",
    "DateEnd": "22.02.2021",
    "Where": "Supermarket"
  },
  {
    "Title": "Go Shopping",
    "DateBeginn": "23.02.2021",
    "DateEnd": "23.02.2021",
    "Where": "Biomarket"
  }
]

To achieve this, I would like to iterate through the dates range and create multiple entities for each date if the difference between start and end dates is more than 1 day.

Answer №1

If you're looking to efficiently add days and format them using Moment, the following code snippet can help achieve that. It involves storing the formatted strings in an array, checking for equality with a specified end date, and ultimately returning the array of day strings:

const calendar = [{
    "Title": "Go Shopping",
    "dates": [{
        "DateBeginn": "19.02.2021",
        "DateEnd": "22.02.2021",
        "Where": "Supermarket",
    },
    {
        "DateBeginn": "23.02.2021",
        "DateEnd": "23.02.2021",
        "Where": "Biomarket"
    }
    ]
}]

const format = 'DD.MM.YYYY';
const calendarData = calendar.flatMap(main => main.dates.flatMap(d => {
    const momentObj = moment(d.DateBeginn, format);
    const endDateStr = d.DateEnd;
    const dateStrs = [d.DateBeginn];
    while (momentObj.format(format) !== endDateStr) {
        momentObj.add(1, 'days');
        dateStrs.push(momentObj.format(format));
    }
    return dateStrs.map(dateStr => ({
        Title: main.Title,
        DateBeginn: dateStr,
        DateEnd: dateStr,
        Where: d.Where,
    }));
}));
console.log(calendarData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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

Whenever I attempt to execute yarn build within next.js, an error always seems to occur

When attempting to compile my next.js project using the yarn build command, an error consistently occurs: Error: Export encountered errors on following paths: /settings at D:\web3\futnft\frontend\node_modules\next\ ...

What's the optimal method to preserve extensive article content with Firebase and Vue.js?

Utilizing Firebase and Vue for my dynamic website, I aim to include a section with numerous article pages structured as follows: <article> <!-- order of these elements will not change --> <h1>Article title</h1> <div id="date ...

Prevent content from occupying unnecessary space below a sticky div

When the "link" on the sticky header is clicked in this scenario, how can I ensure that the linked content item (#mypara) appears below the sticky div rather than directly underneath it where it may be hidden? $(document).ready(function() { $(window ...

Tips for delivering exceptional service at the module level:

I've been working on implementing a provider for a library module that triggers my factory provider when added. However, I've encountered an issue where the provider doesn't seem to execute the console.log, indicating that it's not runn ...

Determine the status of the menu in React select by checking on key press events if it is open

In my project, I am utilizing react-select for the select elements. I'm curious if there's a way to detect the "open" or "closed" state of the menu through a keydown event in the select (either on the select input or within the menu). The versi ...

Organizing a PHP array of dates to create an annual overview

Trying to figure out how to generate a summary of transactions for each month using the data from a PHP array. Desired outcome (disregarding formatting): ------------------------------------------- | December 2009 | 12 | | January ...

What is the best way to input multiple values using scanf and store them in an array?

Imagine a matrix with dimensions NxN, where N falls between 2 and 10, on which you can place chess pieces. Only one piece can occupy each field. The program instructs the user to input the size of the table, followed by the positions of the chess pieces in ...

Trouble obtaining output from chrome.tabs in browser console

Currently, I am experimenting with the browser's console and attempting to retrieve all the details of the active tabs. In order to do so, I open the browser's console and input the following: However, I encountered the following error: VM713:1 ...

Obtain various Angular.js controllers for multiple <td> elements within a single <tr> tag

I am attempting to include multiple angular controllers within the same tr tag. However, I am facing an issue with Chrome rewriting the table and not allowing any element between tr and td in the HTML hierarchy. Currently, I have different colors represen ...

Combining several 2D arrays to create a single 3D array in Python

Currently, I am working with multiple files that can be treated as 2D arrays and accessed with ease. My goal is to combine these 2D arrays into a single 3D array. For instance, if there are a total of 10 files with shapes of (100, 100) each, combining them ...

Eliminate rows in an HTML table that contain "undefined" using Javascript

I am facing an issue with my HTML table created using JS. Despite not having any corresponding data in the JSON source, several rows are filled with "undefined" values in the output. These rows need to be removed. Here is the JS code: const requestUrl9 = ...

Merging Angular with jQuery: Organizing jQuery into a distinct file leads to the error message 'Property 'top' cannot be read because it is undefined.'

My project is based on AngularJS, and I've been trying to incorporate a jQuery code for a sticky sidebar feature. Strangely enough, when I tested my code on Plunkr, it works perfectly fine. However, when I try to implement it in my actual project, it ...

The Angular JS validation feature does not seem to be functioning correctly when used in conjunction with Bootstrap's

I'm currently working on a form that utilizes AngularJS and Bootstrap for validation. Everything was functioning properly until I introduced typeahead functionality - the validation no longer triggers when selecting values from typeahead. Is there a ...

Struggling to combine column vectors in Python to create a 2D array. Having trouble getting it to work

As a newcomer to Python, I am facing a challenge in performing a task that I have previously done in MATLAB. The task involves taking 43,200 single data points, which are integers represented as decimals, and applying a fast Fourier transform on "windows" ...

sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays? Below is an example to help explain the process. To filter the data, use startnumber and endnumber in the query. const data = [ { "name": "x", "points": [ [100, 50, 1], //[number, value ...

Using NicEdit for uploading to your personal server

I'm having trouble uploading images using the NicEdit WYSIWYG editor on my own server. When I click on the upload image button, it redirects me to another site where I can upload the image: imgur dot com You can find a demo of this here: However, I ...

ways to run php script based on screen resolution or size

I have 2 php files that I need to execute based on screen size. include_once('large.php'); include_once('small.php'); The condition is to run large.php when the screen size is greater than 992px, and small.php when the screen size is ...

Recommendations tailored to the user's search query

I am facing an issue with my website. Users can input the name of an Artwork in a search bar, and using Google APIs, I provide them with the title, image, and other helpful details. Additionally, there are e-books on my site with useful information for th ...

Automatically resizing textures in Three.JS with WebGL

Seeking assistance to overcome a challenge :) I am using Three.JS to showcase high-resolution equirectangular images on a sphere (20000x10000 pixels). Image quality is crucial for my web application, and bandwidth is not a concern. My issue is that ThreeJ ...

AngularJS redirection to a different state by utilizing a URL

When I need to direct a user to a specific state, typically I would use the following code: $state.go('state_name'); $state.transitionTo('state_name'); This method usually takes users to /state_name. However, there is one particular s ...