How would you do this kind of transformation in a functional way with underscore.js? I've repeated the following pattern several times lately, and it seems kind of ugly to me.
var fruitList = [
{ id:1, name:lime, color:green, size:small },
{ id:2, name:banana, color:yellow, size:large },
{ id:3, name:lemon, color:yellow, size:small },
{ id:4, name:papaya, color:green, size:large },
{ id:5, name:kiwi, color:green, size:small },
{ id:6, name:apple, color:green, size:small },
{ id:7, name:pear, color:yellow, size:small },
{ id:8, name:grape, color:green, size:small },
{ id:9, name:mango, color:yellow, size:large },
{ id:10, name:honeydew, color:green, size:large }
],
fruitByColorThenSize = {};
jQuery.each(fruitList, function (fruit) {
if (!fruitByColorThenSize[fruit.color]) {
fruitByColorThenSize[fruit.color] = {};
}
if (!fruitByColorThenSize[fruit.color][fruit.size]) {
fruitByColorThenSize[fruit.color][fruit.size] = {};
}
fruitByColorThenSize[fruit.color][fruit.size][fruit.id] = fruit.name;
});
fruitByColorThenSize would then look similar to this:
{
yellow: {
large: {
2: 'banana',
9: 'mango'
},
small: {
3: 'lemon',
7: 'pear'
}
},
green: {
large: {
4: 'papaya',
10: 'honeydew'
},
small: {
1: 'lime',
5: 'kiwi',
6: 'apple',
8: 'grape'
}
}
}