首页 > 解决方案 > 无法将数组过滤到数组中

问题描述

我有类别数组,其中包含专业化的对象数组。当我试图按专业过滤它时,出现了问题(不能更改并保存所有数据的类别列表,它也发生了变化。当我从数据搜索列表中删除字母时不会回来)。我尝试了很多方法,最后代码变成了这样(我知道这不是好的代码,但我尝试了很多东西,只是打字很累);

这是我的过滤方法:

this.setState(prevState => {
  const { categories } = prevState;

  let filtered = [];

  for (let i = 0; i < categories.length; i++) {
    let newCategory = categories[i];
    const { specializations } = categories[i];
    let newSpecs = [];
    for (let j = 0; j < specializations.length; j++) {
      const { specName } = specializations[j];
      if (specName.indexOf(search) !== -1) {
        newSpecs.push(specializations[j]);
      }
    };
    newCategory.specializations = newSpecs;
    if (newSpecs.length>0) {
      filtered.push(newCategory);
    }
  }

  return {resultCategories:filtered}
});

这就是我渲染的方式:

category.specializations.map(
    (spec, index) =>
      (index < 5 || collapsed[cat_index]) && (
        <Text
          onPress={() =>
            this.props.navigation.navigate("CreateOrderSecond", {
              spec: spec.id
            })
          }
          style={styles.specs}
          key={index}
        >
          {spec.specName}
        </Text>
      )
  );

类别的外观:

Category{
 avatar Image{...}
 categoryName   string
 created    string($date-time)
 id integer($int64)
 lastUpdated    string($date-time)
 specializations    [Specialization{
                       avatar   Image{...}
                       created  string($date-time)
                       id   integer($int64)
                       lastUpdated  string($date-time)
                       masterName   string
                       specName string
                     }]
 }

标签: javascriptarraysreactjsreact-native

解决方案


你可以试试这个

category = {
  specializations : [
    {
      created : 2312121,
      id   : 1,
      lastUpdated  : "24-01-2020",
      masterName   : "ProductOne",
      specName :  "Food"
    },
    {
      created : 2312121,
      id   : 1,
      lastUpdated  : "24-01-2020",
      masterName   : "ProductTwo",
      specName :  "Sopping"
    },
    {
      created : 2312121,
      id   : 1,
      lastUpdated  : "24-01-2020",
      masterName   : "ProductThree",
      specName :  "Food"
    }
  ]
}
searchValue = "Food"
let results = category.specializations.filter(specialization => specialization.specName === searchValue)


console.log(results)


推荐阅读