如何将 Lodash orderby 与自定义函数一起使用?



我正在使用Lodash的orderby根据键属性对许多元素进行排序。

我想通过另一个属性(容量(对它们进行优先级排序,该属性(容量(是从 0 到 9 的数字。容量为 0 的项目应在末尾排序,所有其他项目应按键排序。

因此,容量属性应转换为布尔值。我想在不更改原始对象或添加新属性或创建新数组的情况下执行此操作。

示例数据:

[
{
"priceChild": 4098000,
"priceAdult": 4098000,
"priceInfant": 998000,
"displayIndex": 4,
"capacity": 5
},
{
"priceChild": 3698000,
"priceAdult": 3698000,
"priceInfant": 898000,
"displayIndex": 5,
"capacity": 1
},
{
"priceChild": 3006000,
"priceAdult": 3980000,
"priceInfant": 461000,
"displayIndex": 6,
"capacity": 0
},
{
"priceChild": 4912000,
"priceAdult": 6522000,
"priceInfant": 715000,
"displayIndex": 7,
"capacity": 9
}
]

这是我现在使用的排序函数:

orderBy(results, 'displayIndex', 'asc');

我想做这样的事情,但这段代码不起作用,因为三元运算符不会为每个项目运行:

orderBy(results, [this.capacity === 0 ? true : false, 'displayIndex'], ['asc', 'asc']);

发现有一种方法可以在 orderby 属性中使用函数:

orderBy(results, [function(resultItem) { return resultItem.capacity === 0; }, 'displayIndex'], ['asc', 'asc']);

最新更新