Lodash groupBy on object preserve键

时间:2014-11-05 04:29:38

标签: javascript lodash

在对象键上使用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函数吗?

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

如果您使用lodash fp,请不要忘记最后一个参数accumulator