[英]Javascript: How to filter object in array
我有一个由 object 组成的数组,它具有 categoryName(string) 字段和一个数组(plants)。
我想使用植物名称进行过滤,最好的方法是什么?
我试过但它只返回植物数组,忽略 categoryName
this.itemList.map(item => item.plants.filter(p=> p.name.toLowerCase().includes(this.searchTerm.toLowerCase())));
结构
[
[
categoryName: "Heating"
plants: Array(2)
0: {plantId: 35, name: "Alston Oven", description: "Oven", plantCategoryId: 2, whenCreated: "1519357215942", …}
1: {plantId: 19, name: "Gregs Oven", description: null, plantCategoryId: 2, whenCreated: "1516830724579", …}
]
[
categoryName: "Refrigeration"
plants: Array(4)
0: {plantId: 13, name: "Fridge 1 ", description: "Walk in fridge" …}
1: {plantId: 5, name: "Fridge 2 Updated", description: "Description of Fridge 2" …}
2: {plantId: 4, name: "Fridge"....}
]
]
在外部数组上使用filter()
,在内部plants
数组上使用some()
。
这不会过滤掉植物阵列中的特定植物,而是保持整个阵列完好无损。 不清楚是否需要过滤子数组
const term = this.searchTerm.toLowerCase(),
res = this.itemList.filter(({plants}) => plants.some(({name}) => name.toLowerCase().includes(term)))
尝试:
this.itemList.map(function(a) {
return {
categoryName: a.categoryName,
plants: a.plants.filter(p => p.name.toLowerCase().includes(this.searchTerm.toLowerCase()))
}}).filter(a => a.plants.length > 0)
请试试这个例子
const searchTerm = "Alston"; const itemList = [ { categoryName: "Heating", plants: [ { plantId: 35, name: "Alston Oven", description: "Oven", plantCategoryId: 2, whenCreated: "1519357215942", }, { plantId: 19, name: "Gregs Oven", description: null, plantCategoryId: 2, whenCreated: "1516830724579", }, ], }, { categoryName: "Refrigeration", plants: [ { plantId: 13, name: "Fridge 1 ", description: "Walk in fridge" }, { plantId: 5, name: "Fridge 2 Updated", description: "Description of Fridge 2", }, { plantId: 4, name: "Fridge" }, ], }, ]; const output = itemList.filter((item) => { return item.plants.map((entry) => entry.name.toLowerCase()).join().includes(searchTerm.toLowerCase()); }); console.dir(output, { depth: null, color: true });
看
如果您只想过滤plants
arrays,则不需要使用map
。 使用forEach()
,然后用过滤后的数组重新分配plants
属性。
this.itemList.forEach(item =>
item.plants = item.plants.filter(p =>
p.name.toLowerCase().includes(this.searchTerm.toLowerCase())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.