Tengo el siguiente objeto:
const myObject = { property1: ['apple', 'peach'], property2: ['blue', 'red'] }Lo que quiero hacer es crear una lista en una tabla donde enumere en cada fila, el nombre de la clave y justo debajo, todos los elementos de la matriz correspondiente. Algo como:
<li>property1</li> <li>apple</li> <li>peach</li> <li>property2</li> <li>blue</li> <li>red</li>Gracias a todos de antemano.
No está muy claro si quieres una lista o una tabla. Pero aquí hay un ejemplo rápido de una lista con viñetas usando sus datos.
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>Documentación adicional
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> )Puedes usar algo como este. El estado está aquí.
const [records, setRecords] = useState( [ { id: 1, content: "property1"}, { id: 2, content: "apple"}, { id: 3, content: "peach"}, { id: 4, content: "property2"}, { id: 5, content: "blue"} ]);El método de devolución está aquí.
return ( <> <ul> { records.map(r => <li> {r.id + " " + r.content} </li> ) } </ul> </> );