我尝试在成对中使用下划线_.groupBy()
和_.sortBy
,问题是最后一个使用从groupBy
返回的键将对象更改为带索引的数组。是否可以保留对象的原始索引(键)?
以下是示例:
我的代码:
var sorted = _.chain(cars).groupBy('Make').sortBy(function(car) {
return car.length * -1;
});
来自groupBy
的结果:
{
"Volvo" : [ "S60", "V40" ],
"Volkswagen" : [ "Polo", "Golf", "Passat" ]
}
来自sortBy
的结果:
[
0 : [ "Polo", "Golf", "Passat" ],
1 : [ "S60", "V40" ]
]
预期结果:
[
"Volkswagen" : [ "Polo", "Golf", "Passat" ],
"Volvo" : [ "S60", "V40" ]
]
答案 0 :(得分:4)
对象在JavaScript中是无序的。如果您需要像对象这样但有序的东西,您可以使用_.pairs
进行转换,然后对对列表进行排序。
_.pairs({
"Volvo" : [ "S60", "V40" ],
"Volkswagen" : [ "Polo", "Golf", "Passat" ]
})
给出:
[
["Volvo", [ "S60", "V40" ]],
["Volkswagen", [ "Polo", "Golf", "Passat" ]]
]
...然后您可以使用_.sortBy
进行排序。如果您将上述内容分配给cars
,那么:
_.sortBy(cars, function(x) { return -x[0].length; });
给出:
[
[ 'Volkswagen', ['Polo', 'Golf', 'Passat' ]],
[ 'Volvo', ['S60', 'V40']]
]