首页 > 解决方案 > 如何优化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]
    }), {})
}

先感谢您。

标签: javascriptlogicjavascript-objects

解决方案


推荐阅读