javascript - 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' }
] } ] } ]
解决方案
累加器是一个数组,而不是一个对象,因此分配给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));
推荐阅读
- javascript - 尝试返回一个新字符串,其中一些字符被其他字符替换
- qt5 - QModelIndex 创建的地点和时间
- python - 范围输出成字符串 | 错误: [
在 0x02229CA0>] - python - Python。按另一个列表中指定的随机集大小对列表进行索引
- php - 在脚本中设置 application/json 内容类型不起作用
- sql-server - 由同一用户帐户登录执行的用户连接计数
- reactjs - 无法从另一个文件导入 React 组件
- javascript - 如何防止 ReactJS onclick 函数在渲染时运行
- javascript - javascript对象数组 - 重新分配
- node.js - 如何在猫鼬中填充对象属性