products
is an array so map
over it should be fine. products
on the other hand is not and therefore map
won't work. You can use, for example, Object.values(products2[0].products)
so you get 1
and 2
in an array and do what you need with it.
const products2 = [
{
category: "Category 1",
products: {
product1: "1",
product2: "2"
},
},
{
category: "Category 2",
products: {
product1: "3",
product2: "4"
},
},
]
const result = products2
.map(product => `${product.category} ${Object.values(product.products).join(' ')}`)
console.log(result)
Same applies in a react component:
render() {
return (
<div>
{products2
.map(product =>
<div>
{product.category}
{Object.values(product.products).map(name => <p>{name}</p>)}
</div>
)
}
</div>
)
}
PS: You don't need to map twice as I did. Mapping only once and returning the div right away is also fine.