【问题标题】:react native turn object array into string array反应原生将对象数组转换为字符串数组
【发布时间】:2021-05-12 05:09:04
【问题描述】:

我现在正在寻找一段时间,如何将对象数组转换为只有值的数组。例如,我有一个包含几家餐厅的数组,在这些餐厅中有一个名为 category 的键。类别可以有多个值,例如 Sushi、Chinese、asian。我想遍历所有对象并从以下位置减少我的数组:

[{
      id: '1',
      title: 'Italian Dream',
      category: 'Pizza, Pasta, Snack',
      opening_hours: '08:00-24:00',
    },
    {
      id: '2',
      title: 'Turkish Man',
      category: 'Döner, Pizza, Lahmacun',
      opening_hours: '08:00-24:00',
    }]



to 



[ Pasta, Snack, Döner, Pizza, Lahmacun]

如果有人能给我任何建议,我会很高兴。

干杯

【问题讨论】:

  • map 用于在 JavaScript 中转换数组中的数据。
  • 所以你想从所有餐厅数组中提取所有类别到另一个数组中?
  • 是的,我想将所有类别提取到一个新数组中
  • 一个更好的模式有用的模型是为category提供一个字符串数组,而不是一个需要为.split的字符串。

标签: arrays reactjs react-native


【解决方案1】:

您可以循环数组并使用 split 函数从字符串中提取类别。

let newArray = [];
oldArray.forEach(restaurant => {
   newArray.push(...restaurant.category.split(', '));
});

// Here newArray contains categories with duplicate values

// You can use Set to avoid duplicate values.
newArray = [...new Set(newArray)];

【讨论】:

    【解决方案2】:
    1. 由于category是一个字符串而不是字符串数组,我们需要.split(', ')
    2. 由于每个数据项有多个类别,我们可以使用 .flatMap 来“组合”或展平本来应该是数组的数组
    3. 我们可以使用new Set(...) 来获取字符串值的唯一列表
    4. 最后使用Array.from(...)Set 转换为Array

    const data = [{
        id: '1',
        title: 'Italian Dream',
        category: 'Pizza, Pasta, Snack',
        opening_hours: '08:00-24:00',
      },
      {
        id: '2',
        title: 'Turkish Man',
        category: 'Döner, Pizza, Lahmacun',
        opening_hours: '08:00-24:00',
      }
    ]
    
    const categories = Array.from(new Set(data.flatMap(x => x.category.split(', '))))
    console.log(categories)

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2021-05-09
      • 1970-01-01
      • 2022-11-02
      • 2019-03-14
      相关资源
      最近更新 更多