简体   繁体   中英

JavaScript - For Loop to add days in a month object - moment.js

I'm trying to assign every day in the month to my object but I'm only get the last day of each month. How should I do to get full month assigned?

function loopRange (startDate, range) {
   let fromDate = moment(startDate)
   let toDate = moment(startDate).add(range, 'month')
   let dates = {}

   for (let m = moment(fromDate); m.diff(toDate, 'days') <= 0; m.add(1, 'days')) {
        dates['month_' + m.format('MM')] = {
           'date': m.format('YYYY-MM-DD')
        }
    }

    return dates
}

Result I want:

dates = {month_11: ['2018-11-01', '2018-11-02', ...]}

You get only the last day because your for-loop advance in day interval.

However, when assign to dic of dates you put the month as the key - so each iteration (within the same month) override the previous key with the new day -> so you get only yhe lasy day of the months...

If you want to have all dates in the time-range as array elements divide on month keys you can use the following code:

for (let m = moment(fromDate); m.diff(toDate, 'days') <= 0; m.add(1, 'days')) 
{
    let month_key = 'month_' + m.format('MM'); 
    if (!dates.hasOwnProperty(month_key))
        dates[month_key] = []; 
    dates[month_key].push(m.format('YYYY-MM-DD'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM