javascript 如何使用时刻使日的值为空

fquxozlt  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(194)

我想在条形图中绘制一周的数据,如果响应对象中没有日期,如何给予空值。我使用moment和lodash groupby来查找一周中的哪一天。

const actionHistory = [
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-13T18:28:12.850Z"
    },
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-11T18:28:12.850Z"
    }
  ];
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const month = groupBy(actionHistory, (dt) => moment(dt?.amtp_takenOn).days());
const result = map(month, (el, i) => ({ value: el?.length, label: weekdays[i - 1], frontColor: '#177AD5' });`

如果我把console.log放到result中,我会得到唯一可用的日期周天数,如下图所示

[{"value":1,"label":"Tue","frontColor":"#177AD5"},{"value":1,"label":"Thu","frontColor":"#177AD5"}]

我的预期输出应该是。

[{"value":0,"label":"Sun","frontColor":"#177AD5"}, 
 {"value":0,"label":"Mon","frontColor":"#177AD5"}, 
 {"value":1,"label":"Tue","frontColor":"#177AD5"}, 
 {"value":1,"label":"Wed","frontColor":"#177AD5"}, 
 {"value":1,"label":"Thu","frontColor":"#177AD5"}, 
 {"value":0,"label":"Fir","frontColor":"#177AD5"},
 {"value":0,"label":"Sat","frontColor":"#177AD5"}]
j2qf4p5b

j2qf4p5b1#

这就行了

const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let result = [{ "value": 1, "label": "Tue", "frontColor": "#177AD5" }, { "value": 1, "label": "Thu", "frontColor": "#177AD5" }];
result = weekdays.map((day, i) => {
  const res = result.findIndex(({ label }) => label === day);   // is label === day
  if (res !== -1) return result.splice(res, 1)[0];              // return the object
  return { "value": 0, "label": day, "frontColor": "#177AD5" }; // else return an object with value 0
})
console.log(result)
du7egjpx

du7egjpx2#

也许这就是你要找的?

const actionHistory = [
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-13T18:28:12.850Z"
    },
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-11T18:28:12.850Z"
    }
  ];
const [start,end]=actionHistory.map(el=>new Date(el.amtp_takenOn).getDay()).sort();
const res="Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",").map((wd,i)=>
  ({value:+(i>=start&&i<=end),label:wd,frontColor:'#177AD5'}));

console.log(JSON.stringify(res));

在我的代码片段中有很多假设:

  • 数组actionHistory的对象中的datetime值被解释为startend日期,我按照工作日值从小到大的顺序对它们进行排序(0到6表示星期日到星期六),因此开始工作日的值将小于结束工作日的值。

"2023-01-13T18:28:12.850Z"是星期五,"2023-01-11T18:28:12.850Z"是星期三。

  • startend定义的跨度内的所有日期将被赋予值1,并且所有其它日期将被赋予值0

相关问题