javascript - ES6 减少到新对象

标签 javascript reactjs ecmascript-6

我有一个包含一年中所有日子的数组,如下所示:

const days = ["2019-01-01", "2019-01-02", "2019-01-03" ...]

我有一个对象保存特定日期的计划和已完成任务:

const tasks = {"2019-01-01": {"planned": 3, "completed": 2,}, "2019-01-03": { "planned": 1, "completed": 0 }, "2019-01-10": { "planned": 1, "completed": 1} ... }

我想要的是一个新对象,它包含所有日期的信息,无论任务是否已计划和完成,如下所示:

const tasksNew = {"2019-01-01": {"planned": 3, "completed": 2}, "2019-02-02": {"planned": 0, "completed": 0} ...}

我知道这在某种程度上适用于 reduce,但我现在无能为力。

最佳答案

在您的days 数组上使用reduce。对于每一天,如果在您的 tasks 对象中找到一个条目,则将此条目添加到累加器,否则返回一个默认条目。

这是 MDN doc on Array.reduce() .

const days = ["2019-01-01", "2019-01-02", "2019-01-03"];
const tasks = {"2019-01-01": {"planned": 3, "completed": 2,}, "2019-01-03": { "planned": 1, "completed": 0 }, "2019-01-10": { "planned": 1, "completed": 1} };

const tasksNew = days.reduce((accum, day) => {
  accum[day] = tasks[day] ? tasks[day] : { planned: 0, completed: 0 };
  return accum;
}, {});

console.log(tasksNew);

关于javascript - ES6 减少到新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616313/

相关文章:

javascript - jQuery/JavaScript - 将变量传递给函数

html - 如何在 React 中为 svg 图像添加颜色

javascript - ES6 中是否有针对 ES5 `module.exports = require(' ./inner.js')` 的任何一行类比?

javascript - Aurelia 从动态添加的元素中删除EventListener

javascript - 使用 Webstorm (Babel) 进行 ES6 调试

javascript - $nin 与 $and 在 Mongoose 中

javascript - 根据是否有内容显示一个 div 元素

javascript - 将参数分配给闭包中的局部变量

reactjs - react +通量: best practice for calling an action after another action?

javascript - ReactJS:类型数组的状态在重新渲染期间被解构为元素