[英]Lodash groupBy on object preserve keys
在对象键上使用Lodash _.groupBy方法时,我想保留键。
假设我有对象:
foods = {
apple: {
type: 'fruit',
value: 0
},
banana: {
type: 'fruit',
value: 1
},
broccoli: {
type: 'vegetable',
value: 2
}
}
我想做一个转换来获得输出
transformedFood = {
fruit: {
apple: {
type: 'fruit',
value: 0
},
banana: {
type: 'fruit',
value: 1
}
},
vegetable: {
broccoli: {
type: 'vegetable',
value: 2
}
}
}
执行transformedFood = _.groupBy(foods, 'type')
给出以下输出:
transformedFood = {
fruit: {
{
type: 'fruit',
value: 0
},
{
type: 'fruit',
value: 1
}
},
vegetable: {
{
type: 'vegetable',
value: 2
}
}
}
注意原始密钥是如何丢失的。 任何人都知道这样做的优雅方式,理想情况下是单行lodash功能?
var transformedFood = _.transform(foods, function(result, item, name){
result[item.type] = result[item.type] || {};
result[item.type][name] = item;
});
如果你使用lodash fp,不要忘记最后一个参数accumulator
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.