Home > database >  How to map through nested objects of Laravel collection in React JS
How to map through nested objects of Laravel collection in React JS

Time:10-12

In my front-end I am trying to map through nested objects which is coming from back-end Laravel collection:

[
  {
    "id": 1,
    "name": "Chips",
    "product_categories_id": 1,
    "category": {
      "id": 1,
      "category": "Chips",
      "brand": "Bombay Sweets"
    }
  },
  {
    "id": 2,
    "name": "Book",
    "product_categories_id": 2,
    "category": {
      "id": 2,
      "category": "Shoe",
      "brand": "Nike",
    }
  }]

I want to display the product name and related category name from nested object. My approach is:

products.map((product)=>{
    console.log(product.name)
    product.category.map((category)=>(
        console.log(category.category)
    ))
})

which is not working at all. I spent huge amount of time to solve yet no luck.

the error it shows:

ProductListContainer.js:58 Uncaught TypeError: item.category.map is not a function

CodePudding user response:

map method works only with Array. You can use product.category.category to access the value.

CodePudding user response:

Finally solved by this:

products.map((product) => {
    console.log(product.name)
    Object.entries(product.category).map(() => (
        console.log(product.category.category, product.category.brand)
    ))
})
  • Related