为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

肥皂起泡泡 2022-01-13 16:47:40
我必须在图表中显示注册用户的每日/每周/每月计数。这是我从后端获得的数据。现在我需要根据视图类型循环遍历数组。我有这样的数据:[  {    "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);})我不确定获得所需结果的最佳方法和最佳方法。有什么建议吗?谢谢!
查看完整描述

1 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您需要处理数据并准备通用逻辑以将数据转换为正确的格式。


您可以使用groupBy并forEach与reduce方法一起准备数据,如下例所示


演示:https ://repl.it/@abhirathore2006/PrepareDataForCharts


const _ = require('lodash');

// use your dataset

let data = [

  {

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

    "count": 0

  },

  {

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

    "count": 4

  }

];


// prepare data beforehand to save re-calculations

data.forEach(d=>{

  d.dateObj = new Date(d.date)

});


// this method will sum all the counts in given group

function 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 method

function 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 object

console.log(groupAndBuild(data,'getMonth','month'))


查看完整回答
反对 回复 2022-01-13
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号