亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從日期數組中獲取每周和每月數據的最佳方法是什么?

從日期數組中獲取每周和每月數據的最佳方法是什么?

肥皂起泡泡 2022-01-13 16:47:40
我必須在圖表中顯示注冊用戶的每日/每周/每月計數。這是我從后端獲得的數據?,F在我需要根據視圖類型循環遍歷數組。我有這樣的數據:[  {    "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 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號