简体   繁体   中英

Filter object keys, inbetween dates

I am trying to test for a date in between a date range using Moment

const startDate = new Date(dates[0].year, dates[0].day, dates[0].month),
  endDate = new Date(
    dates[lastItemIndex - 1].year,
    dates[lastItemIndex - 1].day,
    dates[lastItemIndex - 1].month
  );
newEvents = Object.keys(events).filter(key => {
  moment()
    .range(startDate, endDate)
    .contains(moment(key).toDate());
});

My events object is:

{
  2018-09-11: {
    dots: Array(4),
    disabled: false,
    selected: true,
    selectedColor: "#00CCCB",
    customStyles: {…}
  }
  2018-09-12: {
    dots: Array(2),
    disabled: false,
    selected: true,
    selectedColor: "#00CCCB",
    customStyles: {…}
  }
  2018-09-13: {
    dots: Array(2),
    disabled: false,
    selected: true,
    selectedColor: "#00CCCB",
    customStyles: {…}
  }
  2018-09-14: {
    dots: Array(1),
    disabled: false,
    selected: true,
    selectedColor: "#00CCCB",
    customStyles: {…}
  }
}

How can I filter my object keys using a date range?

Your code is fine, except, it doesn't set the filtered events anywhere. You can either modify your code to set newEvents like newEvents[key] = events[key] , or you can use reduce like this.

const dateRange = moment().range(startDate, endDate),
newEvents = Object.keys(events).reduce((output, dateString) => {
    dateRange.contains(moment(dateString).toDate()) && (output[dateString] = events[dateString])
    return output
}, {})

Please note, I have moved dateRange outside the loop for efficiency, but it is actually not required. Also, I have not changed the date range logic. But momentjs is not required here, like @Abhay said in the comments, you can simply use timestamps.

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