嵌套 属性 上的 lodash orderBy

lodash orderBy on nested property

我正在使用 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']);

看来你点错了属性 value.

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

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

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

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

一个简单的示例,说明如何在未定义的情况下按另一个 属性 排序:

import _ from "lodash";

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

参考: