Lodash property iteratee on array of array

The name of the picture


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.


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.


prices.currency


prices


prices[0].currency



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


prices[x].currency


_.some(xxx)





Do you have to use lodash? You could achieve this easily in standard Javascript
– CertainPerformance
2 hours ago





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
2 hours ago





JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.
– T.J. Crowder
2 hours ago





@T.J.Crowder yes, ok, it was a notation abuse. I'm dealing with a JS object corresponding to the JSON I posted
– user2340612
2 hours ago




1 Answer
1



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


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





Exactly how I'd do it.
– T.J. Crowder
2 hours ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions