按javascript中的属性对对象进行分组
问题描述:
如何转换:
[
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
]
进入:
[
{type: 'fruit', foods: ['apple', 'banana']},
{type: 'vegetable', foods: ['potato']}
]
使用javascript或下划线
using javascript or underscore
答
假设原始列表包含在名为 list
的变量中:
Assuming the original list is contained in a variable named list
:
_
.chain(list)
.groupBy('type')
.map(function(value, key) {
return {
type: key,
foods: _.pluck(value, 'food')
}
})
.value();