javascript - Lodash groupBy on object preserve keys -
when using lodash _.groupby method on objects keys, want preserve keys.
suppose have object:
foods = { apple: { type: 'fruit', value: 0 }, banana: { type: 'fruit', value: 1 }, broccoli: { type: 'vegetable', value: 2 } }
i transformation 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 next output:
transformedfood = { fruit: { { type: 'fruit', value: 0 }, { type: 'fruit', value: 1 } }, vegetable: { { type: 'vegetable', value: 2 } } }
notice how original keys lost. know of elegant way this, ideally in single line lodash function?
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
javascript lodash
No comments:
Post a Comment