我正在尝试处理从API接收到的数据,它需要根据{{1}像category
,country
和city
这样的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
}
]
答案 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))