user2340612
user2340612

Reputation: 10704

Lodash property iteratee on array of array

Let's imagine I have the following JSON object:

[
    {
        "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
            }
        ]
    },
    ...
]

I'd like to use Lodash to check if there's any object having the price with "GBP" currency, so I wrote the following:

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

However, it always returns false.

My guess is that it is not able to get the prices.currency property since prices is an array of objects, so Lodash doesn't know which of the objects to check. I know I could do something like prices[0].currency, but it would work only in this specific case, where GBP is the first price.

Is there a sort of "wildcard" to say "any of the array items" (like prices[x].currency), or I need to extract the inner objects first and then use _.some(xxx)?

Upvotes: 0

Views: 184

Answers (1)

Zenoo
Zenoo

Reputation: 12880

You could do it without lodash using too Array#some :

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

Demo:

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);

Upvotes: 3

Related Questions