我们可以通过对象的键来实现对对象数组的分组,其中键也是一个数组吗?
[
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
分组后的对象中想要的结果:
{
"fruits": [
{
"name": "Apple",
"tags": ["fruits"]
},
{
"name": "Orange",
"tags": ["fruits"]
},
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
],
"vegetables": [
{
"name": "Tomato",
"tags": ["fruits", "vegetables"]
}
]
}
非常欢迎 Vanilla 或 Lodash 解决方案!
编辑
谢谢大家,这是我最终使用的:
const groupBy = key => array =>
array.reduce((obj, el) => {
el[key].forEach(k => {
obj[k] = obj[k] || []
obj[k].push({ ...el })
})
return obj
}, {})
const groupBySomething = groupBy(`something`)
const grouped = groupBySomething(data)
GCT1015
茅侃侃
呼如林
相关分类