1
i have two arrays of objects
fetch1= [{
    "A": 10
    "X": mac
},
{
    "A": 20
    "X": Hp
}]
fetch2=[{
    "B": 30
    "Y": windows
},
{
    "B":40
    "Y": macfee
}]

Output should be like table

A B
10 30
20 40

First "A" column in a table should display 10 & 30.
Second "B" column in a table should display 20 & 40.
Example:

 <ModalBody>
                <Table>
                  <thead>
                    <tr>
                      <th>A</th>
                      <th>B</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                    {fetch1.map(obj => {
                      return <tr >{obj.A}</tr>;
                   })}                      
                   {fetch2.map(obj => {
                      return <td >{obj.B}</td>;
                   })}
                   </tr>
                  </tbody>
                </Table>
              </ModalBody>
AEM
  • 1,354
  • 8
  • 20
  • 30
Raghu
  • 51
  • 2

1 Answers1

1

Had a similar problem. Modified my code for your situation. I also added some checks in case the arrays are different sizes. If they are we set default values {A: -1, B: -1}. You can remove the additional code if you don't need it.

The most important line would be this ({...(smallestArray[index] ? smallestArray[index] : {A: -1, B: -1}), ...val}); where we merge the two arrays into one.

const genericTable = (props) => {
  const fetch1 = props.fetch1;
  const fetch2 = props.fetch2;
  // if arrays can be different sizes, don't know if this is your case
  const largestArray = fetch1.length > fetch2.length? fetch1 : fetch2;
  const smallestArray = fetch1.length > fetch2.length? fetch2 : fetch1;
  const newArray = largestArray.map((val, index) => 
      ({...(smallestArray[index] ? smallestArray[index] : {A: -1, B: -1}), ...val});
  return (
    <ModalBody >
      <thead>
        <tr>
          <th>A</th>
          <th>B</th>
        </tr>
      </thead>
      <tbody>
        {newArray.map((item, index) => (
          <tr key={index}> // change index key
            <td>{item.A}</td>
            <td>{item.B}</td>
          </tr>
        )}
      </tbody>
    </>
  );
};
Hozeis
  • 1,542
  • 15
  • 36