【发布时间】:2020-08-09 10:03:03
【问题描述】:
我正在尝试对我的应用进行高级搜索,它有一个 stores 对象数组,每个 store 都是一个对象,每个 store 都有一个包含该 store 项目的对象数组,(每个 item 都是目的)。 (我将保留 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)
})
})
希望有人理解我想如何过滤商店,谢谢
【问题讨论】:
-
你的预期输出是什么?
-
在这种情况下,用户输入“tomato”,输出应该是
[{name:"tomato", quantity:"145", unit:"g"}] -
并且
store数组中有多个对象? -
@SajeebAhamed 是的
-
如果商店看起来像这样-
let stores = [ { name:"", type:"", items:[ {name:"tomato", quantity:"145", unit:"g"}, {name:"other items here", quantity:"45", unit:"kg"}, {name:"example item", quantity:"74", unit:"l"}, ] }, { name:"", type:"", items:[ {name:"tomato", quantity:"145", unit:"g"}, ] } ];
标签: javascript arrays object filter