0

I have a list of objects:

const products2 = [
    {category: "Category 1", products:
        {
            product1: "1",
            product2: "2"
        }
    },
    {category: "Category 2", products:
        {
            product1: "3",
            product2: "4"
        }
    },
]

How can I render it in a div? Tried to map it but it didn't work :(

Thanks, Kuba

Jakub Matwiejew
  • 107
  • 2
  • 11

1 Answers1

0

products is an array so map over it should be fine. products on the other hand is not and therefore map won't work. You can use, for example, Object.values(products2[0].products) so you get 1 and 2 in an array and do what you need with it.

const products2 = [
  {
    category: "Category 1",
    products: {
      product1: "1",
      product2: "2"
    },
  },
  {
    category: "Category 2",
    products: {
      product1: "3",
      product2: "4"
    },
  },
]

const result = products2
  .map(product => `${product.category} ${Object.values(product.products).join(' ')}`)


console.log(result)

Same applies in a react component:

render() {
   return (
     <div>
        {products2
          .map(product =>
            <div>
              {product.category}
              {Object.values(product.products).map(name => <p>{name}</p>)}
            </div>
          )
        }
     </div>
   )
}

PS: You don't need to map twice as I did. Mapping only once and returning the div right away is also fine.

Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
  • Great thank you! and how abut:
    Category 1

    1

    2>

    Category 2

    1

    2>

    – Jakub Matwiejew Jan 14 '18 at 12:15
  • Awesome! is it also possible to use conditioner rendering with that? I've got a text in props from a search bar. I tried to use "...indexOf(searchText)<0 return false" but it doesn't work – Jakub Matwiejew Jan 14 '18 at 15:06
  • @JakubMatwiejew yes, it is possible. Check [ReactJS](https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator) docs. They have an explanation around conditional rendering :) – Hemerson Carlin Jan 14 '18 at 18:42