如何通过自定义函数使用Lodash orderby?

时间:2018-09-02 07:49:51

标签: javascript lodash

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

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

因此,应将Capacity属性转换为布尔值。我想做到这一点而无需更改原始对象,添加新属性或创建新数组。

样本数据:

    [
      {
        "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']);

2 个答案:

答案 0 :(得分:1)

发现在orderby属性中可以使用函数:

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

答案 1 :(得分:0)

我只是在下面的代码片段中进行了编写,其工作正常。请检查并让我知道。您可以在map函数内部实现容量逻辑。

const sample = [
    {
        priceChild: 4098000,
        priceAdult: 4098000,
        priceInfant: 998000,
        displayIndex: 4,
        seat: 5
    },
    {
        priceChild: 3698000,
        priceAdult: 3698000,
        priceInfant: 898000,
        displayIndex: 5,
        seat: 1
    },
    {
        priceChild: 3006000,
        priceAdult: 3980000,
        priceInfant: 461000,
        displayIndex: 6,
        seat: 0
    },
    {
        priceChild: 4912000,
        priceAdult: 6522000,
        priceInfant: 715000,
        displayIndex: 7,
        seat: 9
    }
];

const randomNumber = () => Math.floor(Math.random() * 9);
const copy = sample.map(obj => ({ ...obj, ...{ capacity: randomNumber() } }));
const result = _.orderBy(copy, ["capacity"], "desc");