从日期数组中获取每周和每月数据的最佳方法是什么?

我必须在图表中显示注册用户的每日/每周/每月计数。这是我从后端获得的数据。现在我需要根据视图类型循环遍历数组。我有这样的数据:


[

  {

    "date": "2019-10-28",

    "count": 0

  },

  {

    "date": "2019-10-29",

    "count": 4

  },

  {

    "date": "2019-10-30",

    "count": 5

  },

  {

    "date": "2019-10-31",

    "count": 2

  },

  {

    "date": "2019-11-01",

    "count": 0

  },

  {

    "date": "2019-11-02",

    "count": 6

  },

  {

    "date": "2019-11-03",

    "count": 0

  },

  {

    "date": "2019-11-04",

    "count": 0

  },

  {

    "date": "2019-11-05",

    "count": 0

  },

  {

    "date": "2019-11-06",

    "count": 0

  },

  {

    "date": "2019-11-07",

    "count": 0

  },

  {

    "date": "2019-11-08",

    "count": 0

  },

  {

    "date": "2019-11-09",

    "count": 0

  }

]

如果是每周视图类型,那么我需要得到类似这样的结果:


[

  {

    "week": 44,

    "count": 15

  },

  {

    "week": 45,

    "count": 13

  },

  {

    "week": 46,

    "count": 3

  },

  {

    "week": 47,

    "count": 13

  }

]

如果每月,那么我需要得到这样的结果:


[

  {

    "10": 100,

    "count": 15

  },

  {

    "11": 45,

    "count": 13

  },

  {

    "12": 460,

    "count": 3

  }

]

使用图书馆时刻,我可以获得这样的周数:


array.forEach((item, index) => {

   var weeknumber = moment(item.date).week();

   console.log("Week ", weeknumber);

})

我不确定获得所需结果的最佳方法和最佳方法。有什么建议吗?谢谢!


肥皂起泡泡
浏览 157回答 1
1回答

守着星空守着你

您需要处理数据并准备通用逻辑以将数据转换为正确的格式。您可以使用groupBy并forEach与reduce方法一起准备数据,如下例所示演示:https ://repl.it/@abhirathore2006/PrepareDataForChartsconst _ = require('lodash');// use your datasetlet data = [  {    "date": "2019-10-28",    "count": 0  },  {    "date": "2019-10-29",    "count": 4  }];// prepare data beforehand to save re-calculationsdata.forEach(d=>{  d.dateObj = new Date(d.date)});// this method will sum all the counts in given groupfunction buildData(data, keyName ){  let result = [];   _.forEach(data, (val, key)=>{    let totalCounts  = val.reduce((acc, curr)=>{        return acc + curr.count;    }, 0)    result.push({[keyName]:key, count:totalCounts})  })  return result;}// this will group data by given output of date methodfunction groupAndBuild(data, dateMethod, groupKey) {  let groupedData = _.groupBy(data, (d)=>{    return d.dateObj[dateMethod]()  })  return buildData(groupedData, groupKey)}// use moment-js or other library to get week number// and replace dateObj with moment objectconsole.log(groupAndBuild(data,'getMonth','month'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript