简体   繁体   English

如何通过在 javascript 中过滤其中的数组来过滤对象数组

[英]How to filter an array of objects by filtering an array inside of it in javascript

I'm trying to make an advanced searching for my app, it has a stores array of objects, every store is an object and every store has an array of objects that holds the items of that store, (every item is an object).我正在尝试对我的应用程序进行高级搜索,它有一个存储对象数组,每个商店都是 object,每个商店都有一个包含该商店项目的对象数组(每个项目都是一个对象)。 (i'll leave the stores array down so u understand what i mean) (我将把 stores 数组放下,这样你就明白我的意思了)

So basically, I want the user to filter the stores by the item names, but i got stuck and whatever i tried didn't seem to be working.所以基本上,我希望用户按项目名称过滤商店,但我被卡住了,无论我尝试什么似乎都不起作用。 here is the code:这是代码:

stores array:存储数组:

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"},
    ]
  }
]

The filtering way I've tried:我试过的过滤方式:

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)
      })
    })

Hope someone understands how i want to filter the stores, thanks希望有人理解我想如何过滤商店,谢谢

Array#filter will return an empty array when no matches are found.未找到匹配项时, Array#filter将返回一个空数组。 This is a truthy value, you can find this by doing .!array.filter(() => false) .这是一个真实的值,你可以通过.!array.filter(() => false)找到它。 You need to call .length on the second filter to be able to determine whether it has found any matches or not, 0 is falsey and anything else is truthy.您需要在第二个过滤器上调用.length才能确定它是否找到任何匹配项, 0为假,其他为真。

 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));

Use efficient Array.some使用高效Array.some

You can try this:你可以试试这个:

 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM