简体   繁体   中英

Lodash groupBy on object preserve keys

When using Lodash _.groupBy method on an objects keys, I want to preserve the keys.

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 = {
    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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM