按javascript中的属性对对象进行分组 [英] Group objects by property in javascript
本文介绍了按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();
这篇关于按javascript中的属性对对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文