javascript - 如何优化reducer功能
问题描述
我有这个功能
const joinCages = arr => {
return arr.reduce((acc, { jaulaId, comunaCode }) => {
if (!acc.hasOwnProperty(jaulaId)) acc[jaulaId] = []
acc[jaulaId].push(comunaCode)
return acc
}, {})
}
输出是这样的:
{
JAU0000001: [ '130109' ],
JAU0000029: [ '100102', '100103' ],
JAU0000017: [ '100304', '100305' ]
}
它能做什么:
从对象数组中创建一个对象,该对象将键“jaula ID”中的“Comuna Code”分组
数据数组
[
{
indexId: 104834,
jaulaId: "JAU0000001",
distributionCenterId: "100",
comunaCode: "130109",
orderType: "Retorno",
regionCode: "13"
},
{
indexId: 104836,
jaulaId: "JAU0000029",
distributionCenterId: "100",
comunaCode: "100102",
orderType: "Retorno",
regionCode: "13"
},
{
indexId: 104837,
jaulaId: "JAU0000029",
distributionCenterId: "100",
comunaCode: "100103",
orderType: "Retorno",
regionCode: "13"
}
]
我想在没有 if 语句的情况下升级该函数并删除 return...Return 您知道吗?
问题是我编码失败,我不知道在哪里或如何做到这一点。
升级功能
const joinCages2 = arr => {
return arr.reduce((acc, { jaulaId, comunaCode }) => ({
...acc,
[jaulaId]: [jaulaId] ? [jaulaId].push(comunaCode) : [comunaCode]
}), {})
}
先感谢您。
解决方案
推荐阅读
- vue.js - 如何在 Vue JS 2 中为历史模式配置 http-server?
- firebase - 在 Flutter 应用中上传到 Firebase 存储时遇到“未创建任何 Firebase 应用”
- reactjs - 反应路由器故障
- reactjs - 使用 mdx-bundler 时将 bundleMDX 返回的代码转换为 RSS 的 HTML 字符串
- postgresql - 无法通过 @Sql 注释自动运行 sql 脚本
- python - python中的替换样本,每个类的样本数量有限制
- c - C 在表达式中间使用不同的数据类型进行算术运算?
- python - 无法在 vs 代码上升级 python
- python - 如何使用 python beautifulsoup 更新 xml 文件
- java - 如何访问活动Android之外的变量