Home > Back-end >  ReactJS how to loop through an object containing arrays to form the desired JSX element
ReactJS how to loop through an object containing arrays to form the desired JSX element

Time:11-27

I am trying to loop through an object where the keys represent the product category and the value represents an array of product objects.

{Computer:[{title:Aftershock}],Car:[{title:BMW},{title:Bentley}]}

Data Type

enter image description here

How can I loop through the data to prepare the JSX elements to display the products in the following format:

  1. For each category create a div
  2. Indicate the category name
  3. For each product within the category, create it's own product div
  4. Indicate the product details

For example

<div>
  <h1>{category}<h1>
    <div>
     <p>{product.title}<p>
     <p>{product.description}<p>
    </div>
</div>

Current code (But it is filled with syntax error, I cant create the JSX element this way)

const compileCategoryOfProducts=(tempCategoryObj)=>{
        let html = [];
        for (const [key, value] of Object.entries(tempCategoryObj)) {
            let categoryContainerHTML = <Row key={key}><h1>Category</h1>
                {secondLoop(value)}
            </Row>;
            html.push(categoryContainerHTML);
            
        }
        return html;
    }

    const secondLoop=(product)=>{
        let jsxElement = [];
        for(let i = 0; i < product.length; i   ){
            jsxElement.push(<Col key={product[i].id}>
                  <div className="productContainer" >
                        <img src={product[i].image}></img>
                        <p>{product[i].title}</p>
                        <p>Description: {product[i].description}</p>
                        <p>Quantity: {product[i].qty}</p>
                    </div>
            </Col>)
        }
        return jsxElement;
    }

CodePudding user response:

Loop through the object keys using Object.keys and then access the nested items. Like this

 const [data] = React.useState({
    Computer: [{ title: 'Aftershock' }],
    Car: [{ title: 'BMW' }, { title: 'Bentley' }],
  });
  return (
    <div>
      {Object.keys(data).map((key) => (
        <div>
          <h1>{key}</h1>
          {data[key].map((product) => (
            <div>
              <p>{product?.title}</p>
              <p>{product?.description}</p>
            </div>
          ))}
        </div>
      ))}
    </div>
  );

Demo

  • Related