首页 > 解决方案 > 如何通过在javascript中过滤其中的数组来过滤对象数组

问题描述

我正在尝试对我的应用程序进行高级搜索,它有一个存储对象数组,每个商店都是一个对象,每个商店都有一个包含该商店项目的对象数组(每个项目都是一个对象)。(我将把 stores 数组放下,这样你就明白我的意思了)

所以基本上,我希望用户按项目名称过滤商店,但我被卡住了,无论我尝试什么似乎都不起作用。这是代码:

存储数组:

let stores = [
  {
    name:"",
    type:"",
    items:[
      {name:"tomato", quantity:"145", unit:"g"},  //this is what i want to filter with
      {name:"other items here", quantity:"45", unit:"kg"},
      {name:"example item", quantity:"74", unit:"l"},
    ]
  }
]

我尝试过的过滤方式:

let userInput = "tomato";


//this outputs the original array without any filtering

    let filteredStores = stores.filter(store=>{
      return store.items.filter(item=>{
        return item.name.includes(userInput)
      })
    })

希望有人理解我想如何过滤商店,谢谢

标签: javascriptarraysobjectfilter

解决方案


Array#filter找不到匹配项时将返回一个空数组。这是一个真实的价值,你可以通过做找到这个!!array.filter(() => false)。您需要调用.length第二个过滤器才能确定它是否找到任何匹配项,0是否为假,其他是否为真。


推荐阅读