Reputation: 1
I have this array data from api and I want to make it in react tsx file using map function
{
"data":{
"cart":{
"1":{
"product_id":1,
"name":"Product 1",
"quantity":1,
"price":"1.00"
},
"2":{
"product_id":2,
"name":"Product 2",
"quantity":1,
"price":"1.00"
}
}
}
}
React Typescript Code (but not working):
(data.cart.map((item:any, key:any) => (
<p>{item.product_id}</p>
<p>{item.name}</p>
<p>{item.quantity}</p>
<p>{item.price}</p>
)))
I want to to fix the react tsx code
Upvotes: 0
Views: 638
Reputation: 1715
The data is nested inside object within cart. You can use Object.Keys
to access keys like 1, 2, 3 ...
Object.keys(data.cart[0]).map((key) => {
let item = data.cart[0][key];
return (
<React.Fragment key={key}>
<p>{item.product_id}</p>
<p>{item.name}</p>
<p>{item.quantity}</p>
<p>{item.price}</p>
</React.Fragment>
)
});
Based on revised question, since you removed array:
Object.keys(data.cart).map((key) => {
let item = data.cart[key];
return (
<React.Fragment key={key}>
<p>{item.product_id}</p>
<p>{item.name}</p>
<p>{item.quantity}</p>
<p>{item.price}</p>
</React.Fragment>
)
});
Upvotes: 1