数组的Lodash属性iteratee

时间:2018-07-26 09:05:00

标签: javascript arrays lodash

假设我有以下JSON对象:

[
    {
        "name": "productA",
        "prices": [
            {
                "currency": "USD",
                "price": 10.0
            },
            {
                "currency": "EUR",
                "price": 9.0
            }
        ]
    },
    {
        "name": "productB",
        "prices": [
            {
                "currency": "GBP",
                "price": 18.0
            },
            {
                "currency": "EUR",
                "price": 20.0
            }
        ]
    },
    ...
]

我想用Lodash检查是否有价格为“ GBP”货币的对象,所以我写了以下内容:

_.some(products, ['prices.currency', 'GBP'])

但是,它总是返回false

我的猜测是,由于prices.currency是对象数组,因此无法获得prices属性,因此Lodash不知道要检查哪个对象。我知道我可以做类似prices[0].currency的事情,但是它仅在这种特殊情况下才有效,其中GBP是第一个价格。

是否存在某种“通配符”来表示“任何数组项”(例如prices[x].currency),还是我需要先提取内部对象然后使用_.some(xxx)

1 个答案:

答案 0 :(得分:3)

您也可以使用Array#some来完成而不用破折号:

let result = data.some(e => e.prices.some(p => p.currency == 'GBP'));
console.log(result);

演示:

const data = [
    {
        "name": "productA",
        "prices": [
            {
                "currency": "USD",
                "price": 10.0
            },
            {
                "currency": "EUR",
                "price": 9.0
            }
        ]
    },
    {
        "name": "productB",
        "prices": [
            {
                "currency": "GBP",
                "price": 18.0
            },
            {
                "currency": "EUR",
                "price": 20.0
            }
        ]
    }
];

let result = data.some(e => e.prices.some(p => p.currency == 'GBP'));
console.log(result);