我正在尝试对我的应用进行高级搜索,它有一个stores对象数组,每个store是一个对象,每个store有一个对象数组,这些对象保存了该store的项目,(每个项目都是目的)。 (我将离开商店的阵列,以便您理解我的意思)
因此,基本上,我希望用户按商品名称过滤商店,但是我被卡住了,无论尝试如何,似乎都行不通。 这是代码:
存储数组:
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)
})
})
希望有人知道我要如何筛选商店,谢谢
答案 0 :(得分:2)
Array#filter
将返回一个空数组。这是一个真实值,您可以通过执行!!array.filter(() => false)
来找到它。您需要在第二个过滤器上调用.length
才能确定它是否找到任何匹配项,0
是虚假的,其他是真实的。
答案 1 :(得分:1)
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 filterdStores = stores.filter(s=>s.items.some(i=>i.name==='tomato'));
console.log(JSON.stringify(filterdStores,null,2));
使用有效的Array.some
答案 2 :(得分:1)
您可以尝试以下方法:
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"},
]
},
{
name:"",
type:"",
items:[
{name:"tomatos", quantity:"14", unit:"kg"},
]
}
];
let UserInput = "tomato";
const res = stores.filter(({items}) => items.find(item => item.name.includes(UserInput)));
console.log(res);
.as-console-wrapper{min-height: 100%!important; top: 0}