react/api - how to parse and map an array inside of api response

6.1k Views Asked by At

I'm trying to parse and map through the array "items" inside of this api response

[
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  }
]

this is what I have tried, it just parse through the response itself but I want to parse through the array inside of this response.

this.props.items.map((item) => {
                return (
                    <Col className='' xs={12} md={4} key={item.id}>
                        <ProductItem handleOnAdd={this.dispachAddToCart.bind(this)} item={item} />
                    </Col>
                );
            })
3

There are 3 best solutions below

0
Adeel Imran On BEST ANSWER

Suppose this is your array;

const response = [
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  },
  {
    "id": "",
    "portal_account_id": "",
    "platform": "",
    "current_date": "2018-07-30T11:27:16+02:00",
    "email": "",
    "items": [
      {
        "itemId": "123",
        "name": "vacuum 1",
        "img": ""
      },
      {
        "itemId": "456",
        "name": "vacuum 2",
        "img": ""
      },
      {
        "itemId": "789",
        "name": "vacuum 3",
        "img": ""
      }
    ]
  }
];

Then in render method do this.

render() {
   return (
      {response.map(item => {
          return (
             <div key={item.id}>
                {item.items.map(product => {
                    return (
                       <div key={product.itemId}>
                          <p>{product.name}</p>
                          <p>path of image{product.img}</p>
                       </div>
                    );
                })}
             </div>
          )
      })}
   );
}

The problem is you get an array of objects, and inside each object there is another array of objects.

2
Sakhi Mansoor On

You are probably getting JSON res from your API. You can destruct items from it and then iterate over it.

render(){
const { items } = this.props.response

 items.map((item)=>{
    return (
      // do the stuff here
    )
   })

}
0
Jun Jie On

Do you mean you just want to parse the first item of the response array:

this.props.items[0].items.map