Lodash groupBy on object save keys

When using the Lodash _.groupBy method for object keys, I want to save the keys.

Suppose I have an object:

foods = { apple: { type: 'fruit', value: 0 }, banana: { type: 'fruit', value: 1 }, broccoli: { type: 'vegetable', value: 2 } } 

I would like to make a conversion to get a conclusion

 transformedFood = { fruit: { apple: { type: 'fruit', value: 0 }, banana: { type: 'fruit', value: 1 } }, vegetable: { broccoli: { type: 'vegetable', value: 2 } } } 

Running transformedFood = _.groupBy(foods, 'type') gives the following result:

 transformedFood = { fruit: { { type: 'fruit', value: 0 }, { type: 'fruit', value: 1 } }, vegetable: { { type: 'vegetable', value: 2 } } } 

Please note that the original keys are lost. Does anyone know of an elegant way to do this, ideally in a single lodash line feature?

+6
source share
2 answers
 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

+7
source

If you are using lodash fp, don't forget the last argument to accumulator .

0
source

Source: https://habr.com/ru/post/977745/


All Articles