Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
Unable to render two-level deep nested object with map

I'm working on this app where I need to render a two-level deep nested-object with map.

The data looks like this:

const categories = [
  {
    catName: "Education",
    subCategory: [
      {
        subCatName: "College"
      },
      {
        subCatName: "Student"
      }
    ]
  },
  {
    catName: "Motivation",
    subCategory: [
      {
        subCatName: "Study"
      }
    ]
  }
];

I have been trying to render these items in two separate divs with headings Categories for category names (catName) and Subcategories for subcategory names (subCatName).

Right now one category is listed under categories and another in subcategories. Also, there are two subcategories headings. I know this is because of nested mapping but I don't know how I can separate these as all of these are dynamic.

Here's how the code looks like:

export default function App() {

  return (

    <div className="App">

      <h1>All Categories</h1>

      <div className="container">

        <h2>Categories</h2>

        {categories.map((item, index) => (

          <div>

            <span>{item.catName}</span>

            <div className="subcategoriesContainer">

              <h4>Subcategories</h4>

              {item.subCategory.map((el, idx) => (

                <span}>{el.subCatName}</span>

              ))}

            </div>

          </div>

        ))}

      </div>

    </div>
  );
}

Here's the CodeSandbox. And here's how it looks like right now:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Assuming you don't need to maintain the relationship between Categories and Subcategories, I would use the React Memoization hook to transform the data into a format that allows for simpler JSX.

In my simplified answer, I am passing your json data as a prop named data, then using useMemo to create a computed property which won't change unless the data prop changes.

const App = ({data})=> {
  const renderData = React.useMemo(()=> {
    
    return data.reduce((acc,item)=> {
      acc.categories.push(item.catName);
      acc.subcategories.push(...item.subCategory.map(i=>i.subCatName));
      return acc;
    },{categories:[],subcategories: []})      

  },[data]);

  // simplified react code.
  return (
     <div>
       <h1>Categories</h1>
       { renderData.categories.map((item,idx)=><span key={item}>{item}</span>) }
       <h1>Sub Categories</h1>
       { renderData.subcategories.map((item,idx)=><span key={item}>{item}</span>) }
     </div>
  )

}

Depending on your application requirements, you can also chose to transform the data outside of your component (for example: if you are retrieving this data via a REST API it may make sense to transform there), in which case you may not need to use memoization.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda