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

385
Vistas
How to create a list from a specific object in React?

I have the following object:

const myObject = {
property1: ['apple', 'peach'],
property2: ['blue', 'red']
}

What I want to do is to create a list in a Table where I list on each row, the key name and right below, every elements of the corresponding array. Something like:

<li>property1</li>
<li>apple</li>
<li>peach</li>
<li>property2</li>
<li>blue</li>
<li>red</li>

Thank you all in advance.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

It's not really clear whether you want a list or a table. But here's a quick example of a bulleted list using your data.

const { useEffect, useState } = React;

const data = {
  property1: ['apple', 'peach'],
  property2: ['blue', 'red']
};

// Simple function to mock an API response
function mockApi() {
  return new Promise(res => {
    setTimeout(() => {
      res(JSON.stringify(data));
    }, 2000);
  });
}

// Create a list, and then `map` over the object
// entries. Use the key as a list heading, and then
// `map` over the values of the array to create a new list.
function Example() {

  // Initialise state
  const [state, setState] = useState(undefined);

  // Get the data after two seconds
  useEffect(() => {
    mockApi()
      .then(res => JSON.parse(res))
      .then(data => setState(data));
  }, []);

  // If there is no state return "No data"
  if (!state) return <div>No data</div>;

  // Otherwise `map` over the object entries
  // setting each key as the header, and `mapping`
  // over the values array
  return (
    <ul>
      {Object.entries(state).map(([key, arr]) => {
        return (
          <li>
            {key}
            <ul>
              {arr.map(el => <li>{el}</li>)}
            </ul>
          </li>
        );
      })}
    </ul>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Additional documentation

  • map

  • Object.entries

about 4 years ago · Santiago Trujillo Denunciar

0

const obj = {
    property1: ['apple', 'peach'],
    property2: ['blue', 'red'],
}

const data = [];

Object.entries(obj).forEach(([key, values]) => {    
  data.push(key)
  if (Array.isArray(values)) {
    data.push(...values)
  }
});

return (
  <ul>
    {data.map(str => <li>{str}</li>)}
  </ul>
)
about 4 years ago · Santiago Trujillo Denunciar

0

You can use something like this one. State is here.

   const [records, setRecords] = useState(
   [
     { id: 1, content: "property1"},
     { id: 2, content: "apple"},
     { id: 3, content: "peach"},
     { id: 4, content: "property2"},
     { id: 5, content: "blue"}
   ]);

Return method is here.

return (
 <>
   <ul>
   {
     records.map(r =>
     <li>  {r.id + " " + r.content} </li>
     )
   }
   </ul>
</>
);
about 4 years ago · Santiago Trujillo 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