Home > other >  How to show nested items from a API list
How to show nested items from a API list

Time:02-07

I have a data in this format

{
  "id": 1,
  "brands": [], // "n" number of items inside this brands 
  "title": "Phone",
  "image": "/image.png",
  "timestamp": "2022-01-30T23:15:45.355411 05:30",
  "updated": "2022-01-30T23:18:05.053914 05:30"
}

Inside the brands data is like this

brands": [{
  "title": "Phone",
  "id": 1,
  "products": [{
    "id": 1,
    "name": "iPhone 13",
    "image": "/image.png",
    "timestamp": "2022-01-30T23:22:11.259452 05:30",
    "updated": "2022-01-30T23:22:11.259452 05:30",
    "variant": "256 Storage",
  }]
}]

I'm able to show up categories fields like title id etc doing this

{ categories.map((items) => (
  <Col key={items.id} sm={12} md={8} lg={4} xl={3} >
    <div>{items.title}</div>
  </Col>
)) }

But onClick I want to show the nested brands to that category , Being new to JS and react, I don't know proper syntax to access to the nested items.

CodePudding user response:

I think something like this could work.

{categories.map(category => (
    <Col key={category.id} sm={12} md={8} lg={4} xl={3} >
        <div>{category.title}</div>
        <h2>Brands</h2>
        <div>
            {category.brands.map(brand => (
                <div>
                    <div>{brand.title}</div>
                    <ul>
                        brand.products.map(product => (
                            <li>
                                <b>{product.name}</b>
                                <b>{product.timestamp}</b>
                                <img src={product.image}/>
                                <span>{product.id}</span>
                            </li>
                        ))
                    </ul>
                </div>
            ))}
        </div>
    </Col>
))}
  •  Tags:  
  • Related