用2个日期之间的日期填充对象数组

时间:2018-12-18 23:43:33

标签: javascript date-fns

我有一个对象数组,如:

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120},
];

我正在使用eachDayformatdate-fns函数来生成和“回填”给定数组在第一个日期和最后一个日期之间存在的所有日期。

eachDay(
  dates[0].date,
  dates.slice(-1)[0].date,
)
  .map(d => ({
    x: d.dateCollected,
    y: dates
      .filter(e => d.dateCollected === format(e, 'MMM DD YYYY')),
  }));

该代码返回所有日期,但是我无法将count值从原始数组获取到“回填”数组中。

预期结果:

const result =  = [
  {x: "Jul 06 2018", y: 10},
  {x: "Jul 07 2018", y: 0},
  {x: "Jul 08 2018", y: 1},
  {x: "Jul 09 2018", y: 0},
  {x: "Jul 10 2018", y: 120},
];

2 个答案:

答案 0 :(得分:1)

根据eachDay的文档,该函数返回字符串值,而不是具有dateCollected属性的对象。

您可以像这样产生期望的结果:

const {eachDay, format} = dateFns; // Just needed for this snippet to run

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120},
];

const result = eachDay(
  dates[0].date,
  dates.slice(-1)[0].date,
).map(x => format(x, "MMM DD YYYY"))
.map(x => ({ x, y: (dates.find(d => d.date === x) || { count: 0 }).count }));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

答案 1 :(得分:1)

您可以通过创建按日期计数的计数来简化操作:

const {eachDay, format} = dateFns;

const dates = [
  {date: "Jul 06 2018", count: 10},
  {date: "Jul 08 2018", count: 1},
  {date: "Jul 10 2018", count: 120}
];

const counts = dates.reduce((memo, {date, count}) => {
  memo[date] = count;
  return memo;
}, {});

const result = eachDay(
  dates[0].date,
  dates.slice(-1)[0].date
)
  .map(d => {
    const x = format(d, "MMM DD YYYY");
    return {x, y: counts[x] || 0};
  })

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>