0

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

user2340612
  • 10,053
  • 4
  • 41
  • 66
  • Do you *have* to use lodash? You could achieve this easily in standard Javascript – CertainPerformance Jul 26 '18 at 09:05
  • No, I don't need to, but I'm using it to write some tests in Postman and I'd like to use it to keep the "style" used for other tests. However if that's not possible/not readable, I can switch back to vanilla JS – user2340612 Jul 26 '18 at 09:07
  • JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jul 26 '18 at 09:08
  • @T.J.Crowder yes, ok, it was a notation abuse. I'm dealing with a JS object corresponding to the JSON I posted – user2340612 Jul 26 '18 at 09:10

1 Answers1

3

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);
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
Zenoo
  • 12,670
  • 4
  • 45
  • 69