reactjsrestapireact-reduxreact-thunk

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


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>
                );
            })

Solution

  • 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.