I have an array that is consisted of object which has categoryName(string) field and an array(plants).
I'd like to filter using plant name, what's the best approach?
I tried with but it only returns plants array, ignores categoryName
this.itemList.map(item => item.plants.filter(p=> p.name.toLowerCase().includes(this.searchTerm.toLowerCase())));
Structure
[
[
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"....}
]
]
Use filter()
on the outer array and some()
on the inner plants
array.
This will not filter out the specific plant(s) within the plants array but keep the whole array intact. It is not clear whether you need to filter the sub array or not
const term = this.searchTerm.toLowerCase(),
res = this.itemList.filter(({plants}) => plants.some(({name}) => name.toLowerCase().includes(term)))
Try:
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)
Please try this example
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 });
See
If you just want to filter the plants
arrays, you don't need to use map
. Use forEach()
, and then reassign the plants
property with the filtered array there.
this.itemList.forEach(item =>
item.plants = item.plants.filter(p =>
p.name.toLowerCase().includes(this.searchTerm.toLowerCase())));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.