首页 > 解决方案 > 从映射对象中删除空数组

问题描述

我正在使用下面的代码段在网格上显示数据`

{this.state.rows.map((qc) => 
   <div className="column table">
       <div className="row label">
           <div className="column-label qc-number hover-false">{}</div>
               <div className="divider"></div>
                    <div className="column-label qc-date-label">{qc.CreatedOn.replace(",","")}</div>
                       <img className="info" src="../ClientApp/images/Info.svg"></img>
                                </div>
                                {qc.BinsByDayByOrchardsQCs.map((qc2) =>
                                    qc2.BinsByDayByOrchardsQCsDefects.map((qc3) =>
                                        <div onChange={this.removeEmpty} className="row table">{qc3.Count}</div>
                                 ))}
                                <div className="row table total">13</div>   
                            </div>)}

`

这会返回相当多的数据,所以我制作了一个简单的 console.log 来反映我返回的数据。

{console.log("console", this.state.rows.map((qc) =>
    qc.BinsByDayByOrchardsQCs.map((qc2) =>
         qc2.BinsByDayByOrchardsQCsDefects)))}

哪个返回

0: []
1: []
2: []
3: [Array(4)]
4: [Array(4)]
5: [Array(4)]
6: [Array(4)]
7: []
8: []
9: [Array(4)]
10: []

如您所见,我得到了很多空对象,React 正在渲染和显示它们。如何删除这些空对象?我知道 array.filter 但我不确定如何将它应用到我的 JSX

编辑:尝试给出的第一个解决方案

{console.log("console", this.state.rows.map((qc) =>
  qc.BinsByDayByOrchardsQCs.filter(({length}) => length > 0).map((qc2) =>
      qc2.BinsByDayByOrchardsQCsDefects)))}

返回

0: []
1: []
2: []
3: []
4: []
5: []
6: []
7: []
8: []
9: []
10: []

与@yourfavouritedev 提供的解决方案结果相同

标签: javascriptarraysreactjsjsx

解决方案


您可以检查属性length

this.state.rows.map(...).filter(({length}) => length > 0);

根据你的做法

{console.log("console", this.state.rows.map((qc) =>
    qc.BinsByDayByOrchardsQCs.map((qc2) =>
      qc2.BinsByDayByOrchardsQCsDefects)).filter(({length}) => length > 0))}

推荐阅读