如何在React Redux应用程序中根据一个属性对数组进行排序,然后对另一个属性进行分组

时间:2018-12-07 11:12:43

标签: javascript reactjs redux underscore.js reducers

我正在尝试处理从API接收到的数据,它需要根据{{1}像categorycountrycity这样的state进行分组}}。另外,根据类似类别的项目display_priority对它们进行排序。我确实尝试过使用JS函数以及display_priority库,但无法获得所需的输出。 API响应:

lodash

必填输出:

[
    {
        "category": {
            "name": "country",
            "display_priority": 1
        },
        "name": "US",
        "display_priority": 2,
        "enabled": false
    },
    {
        "category": {
            "name": "city",
            "display_priority": 3
        },
        "name": "Greenville",
        "display_priority": 1,
        "enabled": true
    },
    {
        "category": {
            "name": "state",
            "display_priority": 2
        },
        "name": "Alabama",
        "display_priority": 2,
        "enabled": true
    },
    {
        "category": {
            "name": "state",
            "display_priority": 2
        },
        "name": "Arizona",
        "display_priority": 1,
        "enabled": false
    },
    {
        "category": {
            "name": "city",
            "display_priority": 3
        },
        "name": "Houston",
        "display_priority": 2,
        "enabled": false
    },
    {
        "category": {
            "name": "country",
            "display_priority": 1
        },
        "name": "Germany",
        "display_priority": 1,
        "enabled": true
    }
]

1 个答案:

答案 0 :(得分:1)

您只需一个Array.reduce并进行对象分解即可轻松获得此结果:

const data = [{ "category": { "name": "country", "display_priority": 1 }, "name": "US", "display_priority": 2, "enabled": false }, { "category": { "name": "city", "display_priority": 3 }, "name": "Greenville", "display_priority": 1, "enabled": true }, { "category": { "name": "state", "display_priority": 2 }, "name": "Alabama", "display_priority": 2, "enabled": true }, { "category": { "name": "state", "display_priority": 2 }, "name": "Arizona", "display_priority": 1, "enabled": false }, { "category": { "name": "city", "display_priority": 3 }, "name": "Houston", "display_priority": 2, "enabled": false }, { "category": { "name": "country", "display_priority": 1 }, "name": "Germany", "display_priority": 1, "enabled": true } ]

const result = data.reduce((accumulator, {category, name, enabled}) => {
  let key = category.name
  accumulator[key] = accumulator[key] || { category: key, list: [] }
  accumulator[key].list.push({name, enabled})
  return accumulator
}, {})
console.log(Object.values(result))