i'm trying to map over an object but I struggle to manage to get the right results
my example array of objects
[
{
"round": 1,
"points": 0,
"colors": [
"#c99e15",
"#b9bbbd",
"#7C0B2B",
"#97CC04",
"#7fffd4"
]
},
{
"round": 2,
"points": 0,
"colors": [
"#c99e15",
"#b9bbbd",
"#7C0B2B",
"#476C9B",
"#ADD9F4"
]
}
]
I'm trying to get a table where I get
ROUND X // POINTS
- color 1
- color 2
- color 3
- etc
ROUND X 1 // POINTS
- color 1
- color 2
- color 3
- etc
etc
my current code looks likes this, but this unfortunately keeps duplicating the results in "colors" values
<ul>
{obj.map((round) => (
<li key={round.round}>{round.round}
<ul>
{obj.map((outerElement) =>
outerElement.colors.map((colors) => (
<li key={colors} style={{ backgroundColor: colors }}>
{colors}
</li>
))
)}
</ul>
</li>
))}
</ul>
CodePudding user response:
Array.map is a function used to return a transformation of an array If you just loop on array without transforming data it s better to used array.forEach
like you already use loop on your object to get round you can use it to loop on colors of the round
<ul>
{obj.forEach((round) => (
<li key={round.round}>{round.round}
<ul>
{round.colors.forEach((colors) => (
<li key={colors} style={{ backgroundColor: colors }}>
{colors}
</li>
))}
</ul>
</li>
))}
</ul>
CodePudding user response:
I don't know why you obj.map((outerElement) => ...)
inside the loop over the same object. you need to map over round.colors
<li key={round.round}>
{round.round}
<ul>
{round.colors.map((color) => (
<li key={color} style={{ backgroundColor: color }}>
{color}
</li>
))}
</ul>
</li>