首页 > 解决方案 > 使用 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)

标签: javascript

解决方案


您可以获得所需值的键和映射。

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; }


推荐阅读