Lodash groupBy on object preserve键

lee*_*489 8 javascript lodash

在对象键上使用Lodash _.groupBy方法时,我想保留键.

假设我有对象:

foods = {
    apple: {
        type: 'fruit',
        value: 0
    },
    banana: {
        type: 'fruit',
        value: 1
    },
    broccoli: {
        type: 'vegetable',
        value: 2
    }
}
Run Code Online (Sandbox Code Playgroud)

我想做一个转换来获得输出

transformedFood = {
    fruit: {
        apple: {
            type: 'fruit',
            value: 0
        },
        banana: {
            type: 'fruit',
            value: 1
        }
    },
    vegetable: {
        broccoli: {
            type: 'vegetable',
            value: 2
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

transformedFood = _.groupBy(foods, 'type')了以下输出:

transformedFood = {
    fruit: {
        {
            type: 'fruit',
            value: 0
        },
        {
            type: 'fruit',
            value: 1
        }
    },
    vegetable: {
        {
            type: 'vegetable',
            value: 2
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意原始密钥是如何丢失的.任何人都知道这样做的优雅方式,理想情况下是单行lodash功能?

Vas*_*huk 8

var transformedFood = _.transform(foods, function(result, item, name){  
        result[item.type] = result[item.type] || {}; 
        result[item.type][name] = item;
});
Run Code Online (Sandbox Code Playgroud)

http://jsbin.com/purenogija/1/edit?js,console