In ES6 using find
or filter
I\'m quite comfortable iterating through to find an element in an array using a value.
However, I\'m trying to get
You have to return something from the callback of the outer find
. In fact, for the inner iteration you shouldn't use find
but rather some that returns a boolean for whether an element matching the condition exists within the arrray:
products.find((product) => {
return product.items.some((item) => {
//^^^^^^
return item.name === 'milk';
});
});
or in short:
products.find(product => product.items.some(item => item.name === 'milk'));
Then check whether find
found something (not null
!) and get its .id
, the result should be 03
. Alternatively, you can filter
for the products containing milk as an item and then map all the results to their id:
products.filter(product =>
product.items.some(item => item.name === 'milk');
).map(product =>
product.id
) // [03]