javascript - 如何通过在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)
})
})
希望有人理解我想如何过滤商店,谢谢
解决方案
Array#filter
找不到匹配项时将返回一个空数组。这是一个真实的价值,你可以通过做找到这个!!array.filter(() => false)
。您需要调用.length
第二个过滤器才能确定它是否找到任何匹配项,0
是否为假,其他是否为真。
推荐阅读
- c# - 在 Docker 容器上配置用户上传的 A1 证书
- ios - 将数据传递给 SearchBar
- python - Python导入是否将所有代码复制到文件中
- java - 如何使用按钮将 JTextField 值添加到字符串数组
- excel - Excel VBA 文本框
- python - 阻止数字变为负数的简单方法
- android - 有没有办法改变片段主题?
- webpack - VSCode 在导入 Sass 文件时不尊重 webpack 的解析别名
- javascript - 带有复选框弹出窗口的JavaScript淡入淡出不起作用
- c++ - IDA Pro Hexrays 反编译器 MEMORY[0x40080] 错误