Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
leejt489 Avatar asked Nov 05 '14 04:11

leejt489


1 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

like image 51
Vasiliy Vanchuk Avatar answered Oct 21 '22 13:10

Vasiliy Vanchuk