Displaying both key and value in 2 separate table columns in jsx from an array of objects in React Hooks

Viewed 20

I found a work around in Hooks for creating a table that displays 2 columns 'Word' and 'Count' in jsx by using an array with 2 indices. However, is there an efficient way to use this from an array of objects and display key and value of each object in each of the columns. For example using this as our wordCountArr state:

  const [wordCountArr, setWordCountArr] = useState([
    {"bingo": 2},
    {"bango": 5},
    {"needless": 1}
  ]);

Current way this is working in Hooks using an array of arrays. I would like to change the below state to match the above state

const App = () => {
  const [wordCountArr, setWordCountArr] = useState([
    ["bingo", 2],
    ["bango", 5],
    ["needless", 1]
  ]);

  return (
    <div>
      <h1>Word Count</h1>
      <table>
        <thead>
          <tr>
            <th>Word</th>
            <th>Count</th>
          </tr>
        </thead>
        <tbody>
          {!!wordCountArr &&
            wordCountArr.map((wordArr, i) => (
              <tr>
                <td>{wordArr[0]}</td>
                <td>{wordArr[1]}</td>
              </tr>
            ))}
        </tbody>
      </table>
    </div>
  );
};

export default App;
0 Answers
Related