如何使用lodash根据值对嵌套数组进行排序?

viz*_*lux 3 javascript arrays sorting filter lodash

我正在学习如何使用lodash库,但是遇到了一个我认为不知道如何解决的问题。我想用lodash对看起来像这样的嵌套数组进行排序:

"results": [
  {
        "id": "12345",
        "name": "toy123",
        "date_created": "2017-08-29T16:10:37Z",
        "date_last_modified": "2019-01-29T17:19:36Z",
        "prices": [
            {
                "currency": "USD",
                "amount": "100.00"
            },
            {
                "currency": "EUR",
                "amount": "88.23"
            },
        ]
    },
    {
        "id": "54321",
        "name": "toy321",
        "date_created": "2017-08-29T16:10:37Z",
        "date_last_modified": "2019-01-29T17:19:36Z",
        "prices": [
            {
                "currency": "USD",
                "amount": "80.00"
            },
            {
                "currency": "EUR",
                "amount": "70.58"
            },
        ]
    },
]
Run Code Online (Sandbox Code Playgroud)

我想基于prices嵌套在给定数组中的数组对数组进行排序。排序将考虑prices.currency和,prices.amount并产生以下输出,其中基于USD和对给定数组进行升序排序amount。我prices.amount遇到的另一个问题是,它是一个字符串,而不是数字。

[
    {
        "id": "54321",
        "name": "toy321",
        "date_created": "2017-08-29T16:10:37Z",
        "date_last_modified": "2019-01-29T17:19:36Z",
        "prices": [
            {
                "currency": "USD",
                "amount": "80.00"
            },
            {
                "currency": "EUR",
                "amount": "70.58"
            },
        ]
  },
  {
        "id": "12345",
        "name": "toy123",
        "date_created": "2017-08-29T16:10:37Z",
        "date_last_modified": "2019-01-29T17:19:36Z",
        "prices": [
            {
                "currency": "USD",
                "amount": "100.00"
            },
            {
                "currency": "EUR",
                "amount": "88.23"
            },
        ]
    },
]
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的好意,当然也感谢您的时间。

Jak*_*ger 5

_.sortBy()方法不支持自定义比较器,应Array.prototype.sort()改为使用。您也不需要解析prices.amountString.prototype.localeCompare()可以为您做比较,它支持带有数字值的字符串。

放在一起,您的实现可能看起来像这样:

results.sort((a, b) => {
    const priceA = _.find(a.prices, { currency: 'USD' });
    const priceB = _.find(b.prices, { currency: 'USD' });
    return priceA.amount.localeCompare(priceB.amount, undefined, { numeric: true });
});
Run Code Online (Sandbox Code Playgroud)