首页 > 解决方案 > Javascript减少变得丑陋未定义

问题描述

我工作了一些对象来提高我的技能。当我粘贴第一个代码并运行它时,我将获得第二个控制台日志。我想按年份和数量分组。首先,你能告诉我,为什么我在 reduce 数组中有很多未定义的。其次,我怎样才能像第三个代码一样减少这个json?你知道我可以在哪里练习这些吗?

现在已经非常感谢你了。

// first code:
const data = 
  [ { year: 2015, name: 'fizz', volume: 1, issue: '1'   } 
  , { year: 2016, name: 'fizz', volume: 2, issue: '2'   } 
  , { year: 2017, name: 'fizz', volume: 3, issue: '3'   } 
  , { year: 2017, name: 'fizz', volume: 3, issue: '3-1' } 
  , { year: 2018, name: 'fizz', volume: 4, issue: '4'   } 
  , { year: 2018, name: 'fizz', volume: 5, issue: '5'   } 
  ]


const reduced = data.reduce((r, o) => {
  r[o.year] = [...r[o.year] || [], o];
  return r
}, []);


console.log(reduced);
//console.log:
[undefined, undefined, undefined, unde..., [{
  issue: 1,
  name: "fizz",
  volume: 1,
  year: 2015
}], [{
  issue: 2,
  name: "fizz",
  volume: 2,
  year: 2016
}], [{
  issue: 3,
  name: "fizz",
  volume: 3,
  year: 2017
}], [{
  issue: 4,
  name: "fizz",
  volume: 4,
  year: 2018
}, {
  issue: 5,
  name: "fizz",
  volume: 5,
  year: 2018
}]]

我想这样做:

// third code
const Expected = 
  [ { 2015: 
      [ { 1: [ { year: 2015, name: 'fizz', volume: 1, issue: '1' } ] } 
      ] 
    } 
  , { 2016: 
      [ { 2: [ { year: 2016, name: 'fizz', volume: 2, issue: '2' } ] } 
      ] 
    } 
  , { 2017: 
      [ { 3: 
          [ { year: 2017, name: 'fizz', volume: 3, issue: '3'   } 
          , { year: 2017, name: 'fizz', volume: 3, issue: '3-1' } 
      ] } ] 
    } 
  , { 2018: 
      [ { 4: 
          [ { year: 2018, name: 'fizz', volume: 4, issue: '4' } 
          ] 
        } 
      , { 5: 
          [ { year: 2018, name: 'fizz', volume: 5, issue: '5' } 
  ] } ] } ] 

标签: javascriptjsonnestedgroupingreduce

解决方案


累加器是一个数组,而不是一个对象,因此分配给o.year数组的一个属性会在其上放置一个具有大索引的属性 - 准确地说是 2015 年。之前的 2014 年元素将是undefined.

分组为一个对象而不是数组,您还必须考虑每年对象内的奇数嵌套对象/数组结构:

// first code:
const data = [
  { year: 2015, name: 'fizz', volume: 1, issue: 1 },
  { year: 2016, name: 'fizz', volume: 2, issue: 2 },
  { year: 2017, name: 'fizz', volume: 3, issue: 3 },
  { year: 2018, name: 'fizz', volume: 4, issue: 4 },
  { year: 2018, name: 'fizz', volume: 5, issue: 5 },
];


const reduced = data.reduce((r, o) => {
  if (!r[o.year]) {
    r[o.year] = {[o.year]: []};
  }
  r[o.year][o.year].push({ [o.volume]: [o] });
  return r
}, {});


console.log(Object.values(reduced));


推荐阅读