Reputation: 493
I'm trying to render data in a second render with JSON data mapping over it. I have to look over two objects to find matching product_ids
What am I doing wrong here?
{
this.props.productGroups.map((productGroup) => {
return (
<TabContainer key={productGroup.id}>
<h3>{productGroup.title}</h3>
{
productGroup.product_ids.map((productId) => {
this.props.products.map((product) => {
if (product.id == productId) {
return (
<div>
test
</div>
)
} else {
console.log('miss')
}
})
})
}
</TabContainer>
)
})
}
On a sidenote, I know this is callback hell, just not to sure on the best way of refactoring this.
Upvotes: 1
Views: 814
Reputation: 1495
@BenSteward's answer is correct. For your side note, there are various ways to lessen the nested maps.
One way would be, instead of looping through product_ids
and loop through products
inside of it, you can just loop through products
and check if that product
's id exits in the specified product_ids
:
(This is a cleaner version of your code with less parenthesis
and braces
)
{
this.props.productGroups.map(productGroup => (
<TabContainer key={productGroup.id}>
<h3>{productGroup.title}</h3>
{this.props.products.map(product => {
if (productGroup.product_ids.includes(product.id)) { /* Note this line */
return <div>test</div>
}
console.log('miss')
})}
</TabContainer>
))
}
I'm sure it's much better in performance and also much more understandable to your future self.
Upvotes: 1
Reputation: 2408
Your first .map() is missing a return before this.props....
return this.props.products.map((product) => {
Upvotes: 1