【问题标题】:how to display arrayof object data in table format using react js如何使用react js以表格格式显示对象数据数组
【发布时间】:2021-10-30 10:14:22
【问题描述】:
i have two arrays of objects
fetch1= [{
    "A": 10
    "X": mac
},
{
    "A": 20
    "X": Hp
}]
fetch2=[{
    "B": 30
    "Y": windows
},
{
    "B":40
    "Y": macfee
}]

输出应该像表格

A B
10 30
20 40

表中的第一个“A”列应显示 10 和 30。
表中的第二个“B”列应显示 20 和 40。
示例:

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

【问题讨论】:

    标签: reactjs react-native reactstrap react-modal


    【解决方案1】:

    遇到了类似的问题。根据您的情况修改了我的代码。我还添加了一些检查,以防数组大小不同。如果是,我们设置默认值{A: -1, B: -1}。如果不需要,可以删除附加代码。

    最重要的一行是({...(smallestArray[index] ? smallestArray[index] : {A: -1, B: -1}), ...val});,我们将两个数组合并为一个。

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

    【讨论】:

      猜你喜欢
      • 2022-11-01
      • 2020-11-11
      • 2013-06-23
      • 2019-05-29
      • 2020-07-30
      • 2014-04-26
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多