代码之家  ›  专栏  ›  技术社区  ›  Saeed

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

  •  0
  • Saeed  · 技术社区  · 8 年前

    我用的是洛达斯的 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']);
    
    2 回复  |  直到 7 年前
        1
  •  17
  •   Saeed    8 年前

    发现了一种在orderby属性中使用函数的方法:

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