Izzy
Izzy

Reputation: 192

Repeat component for each key and value in Map

I have a JavaScript Map of key/value pairs. I want to repeat render some React components, to display each key/value from the Map inside a table. I'm trying it this way, but I don't get any rows displayed if the myMap contains the following entries:

run: 2
test: 2

enter image description here

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>
  )
};

My getMyMap function:

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;
}

What is a highly performant, elegant way to iterate the Map and repeat render components with the key+value of each item in the Map

Upvotes: 0

Views: 83

Answers (2)

poo
poo

Reputation: 1230

Hey This might be helpful I used a sample code at my end:

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>
  );
};

I used basic HTML tags as was not sure which library you were using.

Upvotes: 0

R4ncid
R4ncid

Reputation: 7129

you can do it like this using 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>
  )
};

Upvotes: 1

Related Questions