0

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

2
  • What's your error message? Commented Jul 16, 2021 at 2:11
  • console log: TypeError: e.map is not a function Commented Jul 16, 2021 at 2:13

1 Answer 1

1

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>
)
});
Sign up to request clarification or add additional context in comments.

1 Comment

original api data: pastebin.com/LDYHF7BU original react typescript code: pastebin.com/61yvU9Pb

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.