javascript - 无法将数组过滤到数组中
问题描述
我有类别数组,其中包含专业化的对象数组。当我试图按专业过滤它时,出现了问题(不能更改并保存所有数据的类别列表,它也发生了变化。当我从数据搜索列表中删除字母时不会回来)。我尝试了很多方法,最后代码变成了这样(我知道这不是好的代码,但我尝试了很多东西,只是打字很累);
这是我的过滤方法:
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
}]
}
解决方案
你可以试试这个
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)
推荐阅读
- python - 我无法让 INSERT INTO 表名等在 Python 3.8 pyodbc MySQL 中工作
- mongodb - Mongo读取大量数据
- php - PHP MySQLi更改为PDO时Android登录失败
- java - 使用 Kafka Stream 中的 State-store(RocksDB) 将一条记录转换为多条记录
- arrays - 将自定义排序应用于打字稿中的对象数组
- ios - Xcode 更新不支持 iphone 5s
- entity-framework-core-3.0 - 如何从 ExecuteSqlInterpolatedAsync 获取查询结果?
- mongodb - 查询具有 n 条记录的集合
- vba - 如何使用按钮打开表单并自动为其中一个字段分配值
- npm - 由于 NPM 的身份验证问题,服务无法在 Kubernetes 上运行