javascript - 使用 map reduce 函数而不是 forEach 重构 JS 对象
问题描述
这种重组可以用高阶函数(map/reduce)来完成吗?test_dat.reduce(func(x,r,)...
我似乎只能用下面显示的 forEach 循环来做到这一点。
const test_dat = {
country: 'Brazil',
timeline: {
cases: {
'4/1/20': 6836,
'4/2/20': 8044,
'4/3/20': 9056,
'4/4/20': 10360,
'4/5/20': 11130,
'4/6/20': 12161,
'4/7/20': 14034,
'4/8/20': 16170,
'4/9/20': 18092,
'4/10/20': 19638,
'4/11/20': 20727,
'4/12/20': 22192,
'4/13/20': 23430,
'4/14/20': 25262,
'4/15/20': 28320,
'4/16/20': 30425,
'4/17/20': 33682,
'4/18/20': 36658,
'4/19/20': 38654,
'4/20/20': 40743,
'4/21/20': 43079,
'4/22/20': 45757
},
deaths: {
'4/1/20': 240,
'4/2/20': 324,
'4/3/20': 359,
'4/4/20': 445,
'4/5/20': 486,
'4/6/20': 564,
'4/7/20': 686,
'4/8/20': 819,
'4/9/20': 950,
'4/10/20': 1057,
'4/11/20': 1124,
'4/12/20': 1223,
'4/13/20': 1328,
'4/14/20': 1532,
'4/15/20': 1736,
'4/16/20': 1924,
'4/17/20': 2141,
'4/18/20': 2354,
'4/19/20': 2462,
'4/20/20': 2587,
'4/21/20': 2741,
'4/22/20': 2906
}
}
}
const restructured = []
let cases_d = test_dat.timeline.cases
let deaths_d = test_dat.timeline.deaths
const keys = Object.keys(cases_d);
keys.forEach(function(key) {
restructured.push({
date: key,
cases: cases_d[key],
deaths: deaths_d[key],
});
});
console.log(restructured)
解决方案
您可以获得所需值的键和映射。
const
data = { country: 'Brazil', timeline: { cases: { '4/1/20': 6836, '4/2/20': 8044, '4/3/20': 9056, '4/4/20': 10360, '4/5/20': 11130, '4/6/20': 12161, '4/7/20': 14034, '4/8/20': 16170, '4/9/20': 18092, '4/10/20': 19638, '4/11/20': 20727, '4/12/20': 22192, '4/13/20': 23430, '4/14/20': 25262, '4/15/20': 28320, '4/16/20': 30425, '4/17/20': 33682, '4/18/20': 36658, '4/19/20': 38654, '4/20/20': 40743, '4/21/20': 43079, '4/22/20': 45757 }, deaths: { '4/1/20': 240, '4/2/20': 324, '4/3/20': 359, '4/4/20': 445, '4/5/20': 486, '4/6/20': 564, '4/7/20': 686, '4/8/20': 819, '4/9/20': 950, '4/10/20': 1057, '4/11/20': 1124, '4/12/20': 1223, '4/13/20': 1328, '4/14/20': 1532, '4/15/20': 1736, '4/16/20': 1924, '4/17/20': 2141, '4/18/20': 2354, '4/19/20': 2462, '4/20/20': 2587, '4/21/20': 2741, '4/22/20': 2906 } } },
{ cases, deaths } = data.timeline,
result = Object.keys(cases).map(date => ({
date,
cases: cases[date],
deaths: deaths[date]
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- python - 如何使用 pyinstaller 从 python 脚本制作 .exe?
- bash - 关闭 bash 终端时如何终止进程?
- google-apps-script - 解析检索到的数据后,此脚本不会填充工作表
- javascript - Firebase 在我输入时逐字母获取数据(不单击“更新”),而不是整个字符串
- c - C 编译器不会注意到错误并自行纠正代码
- switch-statement - ifelse 预期的声明或声明
- php - 我是否正确使用了 file_get_contents?
- ios - 当设置为“全部链接”时,DependencyService.Get 返回 null
- ios - 无法将正确的信息从 tableview 传递到新的视图控制器
- javascript - NodeJS - 找不到 JSON 文件