Home > Software engineering >  Repeat component for each key and value in Map
Repeat component for each key and value in Map

Time:05-12

I have a JavaScript 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

CodePudding user response:

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

CodePudding user response:

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.

  • Related