你将如何使用 underscore.js 以一种功能性的方式进行这种转换?我最近多次重复以下模式,这对我来说似乎有点难看。
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 看起来与此类似:
{
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'
}
}
}