【问题标题】:lodash orderBy on nested property嵌套属性上的 lodash orderBy
【发布时间】:2016-04-13 18:00:03
【问题描述】:

我正在使用v4.11.0。 我想根据milliseconds 属性对对象进行排序。 这是数组:

[
    {
        "name": "bug12755.xml",
        "list": "bugs42",
        "start-date": "2015-09-14",
        "age": {
            "text": "7 months",
            "milliseconds": 18381227304
        }
    },
    {
        "name": "bug12922.xml",
        "list": "bugs42",
        "start-date": "2015-08-27",
        "age": {
            "text": "8 months",
            "milliseconds": 19936427304
        }
    },
    {
        "name": "bug13183.xml",
        "list": "bugs50",
        "start-date": "2015-08-27",
        "age": {
            "text": "8 months",
            "milliseconds": 19936427305
        }
    }
]

我缺少关于 iteratee 函数的一些基本内容。我有这个,但似乎没有对数组进行排序。提前致谢!

 _.orderBy(list, function(item) {
            return item.age.value;
        }, ['desc']);

【问题讨论】:

    标签: lodash


    【解决方案1】:

    您似乎是按错误的属性value 订购的。

    _.orderBy(list, item => item.age.milliseconds, ['desc']);
    

    【讨论】:

    【解决方案2】:

    https://codepen.io/a2qube/pen/pKYrgN

    一个关于如何使用 Lodash: orderBy 根据内部属性进行排序的简单示例。

    hotels = _.orderBy(hotels, 'account.id', 'desc');

    【讨论】:

    • 这种方法要好得多,因为它更简单,并且以更少的复杂性完成工作。
    【解决方案3】:

    一个简单的例子,说明如何在另一个属性未定义时按另一个属性排序:

    import _ from "lodash";
    
    const orderItems = (items) => _.orderBy(items, (item) => item.displayName || item.name, ["asc"]);
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-18
      • 2019-12-11
      • 1970-01-01
      • 2017-01-10
      • 2018-07-31
      • 2018-01-03
      • 2021-10-23
      • 2019-07-29
      相关资源
      最近更新 更多