[英]Lodash groupBy on object preserve keys
When using Lodash _.groupBy method on an objects keys, I want to preserve the keys. 在对象键上使用Lodash _.groupBy方法时,我想保留键。
Suppose I have the object: 假设我有对象:
foods = {
apple: {
type: 'fruit',
value: 0
},
banana: {
type: 'fruit',
value: 1
},
broccoli: {
type: 'vegetable',
value: 2
}
}
I would like to do a transformation to get the output 我想做一个转换来获得输出
transformedFood = {
fruit: {
apple: {
type: 'fruit',
value: 0
},
banana: {
type: 'fruit',
value: 1
}
},
vegetable: {
broccoli: {
type: 'vegetable',
value: 2
}
}
}
Doing transformedFood = _.groupBy(foods, 'type')
gives the following output: 执行transformedFood = _.groupBy(foods, 'type')
给出以下输出:
transformedFood = {
fruit: {
{
type: 'fruit',
value: 0
},
{
type: 'fruit',
value: 1
}
},
vegetable: {
{
type: 'vegetable',
value: 2
}
}
}
Notice how the original keys are lost. 注意原始密钥是如何丢失的。 Anyone know of an elegant way to do this, ideally in a single line lodash function? 任何人都知道这样做的优雅方式,理想情况下是单行lodash功能?
var transformedFood = _.transform(foods, function(result, item, name){
result[item.type] = result[item.type] || {};
result[item.type][name] = item;
});
http://jsbin.com/purenogija/1/edit?js,console http://jsbin.com/purenogija/1/edit?js,console
如果你使用lodash fp,不要忘记最后一个参数accumulator
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.