Tengo un mapa JavaScript de pares clave/valor. Quiero repetir renderizar algunos componentes de React, para mostrar cada clave/valor del Mapa dentro de una tabla. Lo estoy intentando de esta manera, pero no se muestra ninguna fila si myMap contiene las siguientes entradas:
run: 2 test: 2 export const KeyValueTable = (props) => { const text = props.text; const myMap = getMyMap(text); return ( <Table> <Head> <Cell><Text>Key</Text></Cell> <Cell><Text>Value</Text></Cell> </Head> {[...myMap].map((keyValuePair) => ( <Row> <Cell><Text>key = {keyValuePair[0]}</Text></Cell> <Cell><Text>value = {keyValuePair[1]}</Text></Cell> </Row> ))} </Table> ) }; Mi función getMyMap :
export const getMyMap = (text) => { var myArray = text.split(" "); var myMap = new Map(); for (let i = 0; i < myArray.length; i++) { const word = myArray[i]; myMap[word] = myMap[word] + 1 || 1; } return myMap; } ¿Qué es una forma elegante y de alto rendimiento de iterar el Map y repetir los componentes de representación con la clave + valor de cada elemento en el Map ?
puedes hacerlo así usando Map.prototype.entries
export const KeyValueTable = (props) => { const myProp = props.myProp; const myMap = getMyMap(myProp); return ( <Table> <Head> <Cell><Text>Key</Text></Cell> <Cell><Text>Value</Text></Cell> </Head> {Object.entries(myMap).map(([key, value]) => ( <Row> <Cell><Text>key = {key}</Text></Cell> <Cell><Text>value = {value}</Text></Cell> </Row> ))} </Table> ) };Hola, esto podría ser útil. Usé un código de muestra en mi extremo:
export const KeyValueTable = (props) => { const map1 = new Map(); map1.set("a", 1); map1.set("b", 2); map1.set("c", 3); console.log(map1); return ( <table> <thead> <tr> <th>Key</th> <th>Value</th> </tr> </thead> <tbody> {[...map1].map((keyValuePair, index) => ( <tr key={index}> <td>key = {keyValuePair[0]}</td> <td>value = {keyValuePair[1]}</td> </tr> ))} </tbody> </table> ); };Usé etiquetas HTML básicas porque no estaba seguro de qué biblioteca estaba usando.