遍历数组并仅选择第一个值TS和React

尝试创建动态过滤器时,它将读取数组并返回一个按钮,然后过滤呈现的数据。我试图让它只显示唯一的过滤器,但不知道如何。我当前的代码:

 const typeFilter = data?.venuesByCountry.map(v => (
    v.venueTypes.map(a =>(
    <>
      <Button onClick={() => filterC(`${a}`)}>{a}</Button>
    </>
    ))
  ))

返回:

["VENUE"]
["RESTAURANT"]
["BAR", "DRINKS", "PUB"]
["BAR", "DRINKS"]
["BAR", "DRINKS"]

但我希望它返回如下内容:

["VENUE"]
["RESTAURANT"]
["BAR"]
["DRINKS"]
["PUB"]

要么:

["VENUE"]
["RESTAURANT"]
["BAR", "DRINKS", "PUB"]

任何帮助将非常感激!

评论
  • het
    het 回复

    您想展平阵列,

      const newArray = data.venuesByCountry.reduce((acc, item) => {
        return acc.concat(item.venueTypes);
      }, [])
    

    如果您的数据如下所示,

    const venuesByCountry = [
        { venueTypes: [1, 2] },
        { venueTypes: [3, 4] },
    ]
    

    then you'll get newArray to be [1,2,3,4]