skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    Finally solved by this:

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

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search