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 a value from a parent array based upon a value from a nested array.
For example, in this data structure:
products: [
{
id: 01,
items: [
{
id: 01,
name: 'apple'
},
{
id: 02,
name: 'banana'
},
{
id: 03,
name: 'orange'
}
]
},
{
id: 02,
items: [
{
id: 01,
name: 'carrot'
},
{
id: 02,
name: 'lettuce'
},
{
id: 03,
name: 'peas'
}
]
},
{
id: 03,
items: [
{
id: 01,
name: 'eggs'
},
{
id: 02,
name: 'bread'
},
{
id: 03,
name: 'milk'
}
]
}
]
If I know the name or id of the object milk, is there a way to find out the id of the element it's nested within?
Currently I have this:
products.find((product) => {
product.find((prod) => {
return prod.name === 'milk';
});
});
Which only returns the object containing milk.
products:example shorter to make it easier for the reader to scan through (and shorten the length of the question).