每个月发生一次

时间:2018-03-08 11:17:26

标签: javascript momentjs

因此,我在过去7个月内每月展示一个显示事件的图表。我使用moment.js这样过去7个月了:



    let dateFrom = [];
    for (var i = 6; i >= 0; i--) {
      dateFrom.push(moment().subtract(i, "months").endOf("month").format("MMMM"));
    }
    console.log(dateFrom);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
&#13;
&#13;
&#13;

我有一个像这样的事件列表,每个事件都有随机的月份:

var eventList = [
  { org: "org1", date: "2018-03-07T09:46:45Z" },
  { org: "org1", date: "2018-01-07T09:46:45Z" },
  { org: "org2", date: "2018-02-07T09:46:45Z" },
  { org: "org2", date: "2018-03-07T09:46:45Z" },
  { org: "org3", date: "2017-03-07T09:46:45Z" },
  { org: "org3", date: "2017-11-07T09:46:45Z" }
]

我想知道每个org每月发生的事件。我想输出应该是这样的(请注意,应避免在过去七个月的范围之外的任何月份):

let result = {
  "org1": {
    "September": 0
    "October": 0
    "November": 0
    "December": 0
    "January": 1
    "February": 0
    "March": 1
  },
  "org2": ...
}

所以我猜想设置会是这样的:

let sevenLatestMonths = [... the months ...]
let events = [{... the events with UTC dates ...}]
let result = {};

我该如何解决?我甚至不知道从哪里开始。 非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

管理解决它,虽然它有点难看

WeekOfTheYear
    let result = {};
    let a = [
              { org: "org1", date: "2018-01-07T09:46:45Z" },
              { org: "org1", date: "2018-01-07T09:46:45Z" },
              { org: "org2", date: "2018-02-07T09:46:45Z" },
              { org: "org2", date: "2018-03-07T09:46:45Z" },
              { org: "org3", date: "2017-03-07T09:46:45Z" },
              { org: "org3", date: "2017-11-07T09:46:45Z" }
						];
    let months = [
                  "September",
                  "October",
                  "November",
                  "December",
                  "January",
                  "February",
                  "March"
                ];
    let monthsObj = {};
    
    months.map((value) => {
        monthsObj[`${value}`] = 0;
        return monthsObj;
      }
    );

    for (var i = 0; i < a.length; ++i) {
    	let orgName = a[i].org;

      if (!result[orgName]) {
        result[orgName] = {};
        Object.assign(result[orgName], monthsObj);
      }
      
      months.forEach(month => {
      
        if (moment(a[i].date).format("MMMM") === month) {
          result[a[i].org][month] += 1;
        }
      })
    }

   console.log(result);