簡體   English   中英

Javascript:如何過濾數組中的 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM