JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented moment.js along with the moment-range plugin but it does not seem to be the root cause of the issue. To tackle the problem of recurring ranges with moment-range, I decided to iterate through my seasonsObject and create new seasons for the next five (or any specified number) years. This is where I have hit a roadblock - my loop is not functioning as expected.

var seasonsObject = {
       low: {
          period: "low",
          seasonStart: "2017-11-01T12:01:00.000Z",
          seasonEnd: "2018-03-15T12:01:00.000Z"
       },
       high: {
         period: "high",
         seasonStart: "2018-06-01T12:01:00.000Z",
         seasonEnd: "2018-08-01T12:01:00.000Z"
       }
    }
var futureSeasons;

for (var i = 0; i < 5; i++) {
    futureSeasons = _.each(seasonsObject,(val) => { 
        val.range = moment.range(moment(val.seasonStart).add(i,'y'), moment(val.seasonEnd).add(i,'y')) 
    });
}

I have verified that the segment using moment.js and moment-range works correctly, therefore, the issue lies within my loop - it appears to stop after i = 0 since only the seasons of the first year are displayed. I attempted replacing _.each() with _.map() and _.mapObject(), but neither provided the desired outcome.

The end goal should be:

futureSeasons: {
    low0: {
        period: "low",
        seasonStart: "2017-11-01T12:01:00.000Z",
        seasonEnd: "2018-03-15T12:01:00.000Z"
    },
    high0: {
        period: "high",
        seasonStart: "2018-06-01T12:01:00.000Z",
        seasonEnd: "2018-08-01T12:01:00.000Z"
    },
    low1: {
        period: "low",
        seasonStart: "2018-11-01T12:01:00.000Z",
        seasonEnd: "2018-03-15T12:01:00.000Z"
    },
    high1: {
        period: "high",
        seasonStart: "2019-06-01T12:01:00.000Z",
        seasonEnd: "2018-08-01T12:01:00.000Z"
    },
    low2: {
        period: "low",
        seasonStart: "2020-11-01T12:01:00.000Z",
        seasonEnd: "2018-03-15T12:01:00.000Z"
    },
    high2: {
        period: "high",
        seasonStart: "2021-06-01T12:01:00.000Z",
        seasonEnd: "2018-08-01T12:01:00.000Z"
    },
    ...
}

I am utilizing Vue.js and plan to encapsulate this behavior in a computed property! Any assistance would be highly valued :-)

Answer №1

Are you looking to achieve this?

window['moment-range'].extendMoment(moment);

var seasonsObject = {
  low: {
    period: "low",
    seasonStart: "2017-11-01T12:01:00.000Z",
    seasonEnd: "2018-03-15T12:01:00.000Z"
  },
  high: {
    period: "high",
    seasonStart: "2018-06-01T12:01:00.000Z",
    seasonEnd: "2018-08-01T12:01:00.000Z"
  }
}


function createFutureSeasons(amount) {
  const futureSeasons = {};
  _.range(0, amount).forEach(y => {
    Object.keys(seasonsObject).forEach(k => {
      const {
        period,
        seasonStart,
        seasonEnd
      } = seasonsObject[k];

      futureSeasons[k + y] = {
        period,
        seasonStart: moment(seasonStart).add(y, 'years').toISOString(),
        seasonEnd: moment(seasonEnd).add(y, 'years').toISOString()
      };
    });
  });
  return futureSeasons;
}

const fseasons = createFutureSeasons(5);
console.log(fseasons);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/3.1.1/moment-range.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

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

By utilizing the window.history.back() function, it takes me four clicks to navigate back one page

I find it peculiar that my back button is using the JS method window.history.back() to return to the previous page. However, I have noticed a strange behavior with this button. When I click on it before the entire document loads, it functions as expected a ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Tips for implementing a repeater item to function beyond the ng-repeat directive

Recently, I decided to play around with AngularJS and now I seem to be facing a small issue with ng-class. Specifically, I'm attempting to change the color of an awesome font icon. <div ng-controller="MyCtrl"> <i ng-class="{'test': ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

Prevent form submission when text fields are empty or dropdown selections are not made

I have a piece of code that is currently working with just one textbox input called 'departname'. However, I now need all input fields to be required and the dropdown menu for 'ACFTREG' (which is populated from a Sharepoint list) should ...

The mysterious plugin "transform-runtime" has been detected in the ".babelrc" file located in "UsersPhpstormProjectseasy-essay"

After downloading a GitHub repository, I came across a file named .babelrc.json with the following contents: { "presets": [ "es2015", "stage-0" ], "plugins": [ "transform-runtime", "add-module-exports", "transform-decorators-lega ...

The Great Gatsby - Unable to access property 'component---src-pages-index-jsx' due to its undefined nature

Attempting to transition my current ReactJS application with a WordPress backend to GatsbyJS has presented some challenges. As a newcomer to GatsbyJS, I diligently followed the setup instructions provided on their website for Windows 10. Despite a successf ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

Exploring the process of passing parameters in Material-UI React styled components

Recently, I developed a new component const CategoryDialog = (props) => { const classes = useStyles(); console.log(props); return ( <div> <Dialog fullScreen open={props.dilaogOpenProp} TransitionCompone ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

I want to learn how to display the rupee symbol instead of the default dollar symbol in AngularJS for specific currency symbols

When using 'currency' in AngularJS, I noticed that a dollar symbol is displayed. How can I change this to show the required currency symbol based on different requirements? Currently, I am looking for information on how to display a rupee symbol ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

Encountered an issue with the ProgressPlugin: TypeError - Unable to access property 'tap' of an undefined element

Encountering a Problem with npm run build Here's the issue at hand Compiling client E:\ui\sheraspace_ui\node_modules\webpack\lib\ProgressPlugin.js:223 compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

The functionality of the bootstrap Dropdown multiple select feature is experiencing issues with the Onchange

Creating a Bootstrap Multiple Select Drop Down with dynamically retrieved options from a Database: <select size="3" name="p" id="p" class="dis_tab" multiple> <?php echo "<option>". $row['abc'] ."</option>"; //Fetching option ...

Encountering a timeout error while using selenium-webdriver and phantomJS

Currently, I am developing my automated test scripts using a combination of selenium-webdriver, phantomJS, and mocha. The script I am working on is written in JavaScript. One requirement is to wait until a specific element becomes completely visible befo ...