从嵌套的地图对象中删除重复项

时间:2019-04-23 01:26:52

标签: javascript arrays reactjs object ecmascript-6

我正在使用看起来像

的嵌套地图在网格上显示数据
{
    this.state.rows.map((qc) =>
        qc.BinsByDayByOrchardsQCs.map((qc2) =>
            qc2.BinsByDayByOrchardsQCsDefects.map((qc3) =>
              {console.log("results", qc3.Defect)}
                <div className="row table">
                    {qc3.Defect}
                </div>
            )
        )
    )
}

哪个返回的数据看起来像这样

results Scuff results Sunburn results Bruise results Hail damage results Scuff results Sunburn results Bruise results Scuff results Sunburn results Hail damage

如何消除重复项?我尝试过

{console.log("unique",[...new Set(qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3.Defect))])} 但这会返回映射对象的每次迭代

1 个答案:

答案 0 :(得分:2)

简单的方法是创建一个数组,在其中推送要打印的元素,然后在打印另一个元素之前检查其是否存在于数组中。

const arr = [];
{
    this.state.rows.map((qc) =>
        qc.BinsByDayByOrchardsQCs.map((qc2) =>
            qc2.BinsByDayByOrchardsQCsDefects.map((qc3) =>
              {!arr.includes(qc3.Defect) && arr.push(qc3.Defect) &&
                (<div className="row table">
                    {qc3.Defect}
                </div>)
              }
            ) 
        )
    )
}