在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ JS 對象數(shù)組根據(jù)多個條件過濾

JS 對象數(shù)組根據(jù)多個條件過濾

比如有個 數(shù)組`let array = [

{
  date: '2016-05-02',
  name: 'Ethan',
  status: 'success',
  total: '81'
},
{
  date: '2016-05-04',
  name: 'Lynn',
  status: 'fail',
  tag: '50'
},
{
  date: '2016-05-01',
  name: 'Kevin',
  status: 'success',
  tag: '20'
}]`

過濾條件:`let filters = {

  name: ['Lynn', 'Kevin'],
  status: ['success']
}`

想要的結(jié)果是同時滿足 name 是 Lynn或者Kevin 同時 status是success的數(shù)據(jù)
請問怎么寫比較有效率 謝謝


補充內(nèi)容:

研究了一會
最初是這樣的 后來感覺太麻煩

     this.array.filter( item => {
          for(let i = 0; i< this.filters.length; i++) {
            console.log(i)
             if(item.name === this.filters[i]) {
               return true
             }
          }
          return false           
        }).filter(.....)

現(xiàn)在的做法

array.filter(item => {
        return (filters.name.length === 0 ? true : filters.name.indexOf(item.name) !== -1) &&
          (filters.tag.length === 0 ? true : filters.tag.indexOf(item.tag) !== -1)
      })

js初學(xué), 希望有更好的方法

回答
編輯回答
傲寒

研究了一會
最初是這樣的 后來感覺太麻煩

     this.array.filter( item => {
          for(let i = 0; i< this.filters.length; i++) {
            console.log(i)
             if(item.name === this.filters[i]) {
               return true
             }
          }
          return false           
        }).filter(.....)

現(xiàn)在的做法

array.filter(item => {
        return (filters.name.length === 0 ? true : filters.name.indexOf(item.name) !== -1) &&
          (filters.tag.length === 0 ? true : filters.tag.indexOf(item.tag) !== -1)
      })

js初學(xué), 希望有更好的方法

2017年11月29日 15:18
編輯回答
傻丟丟
let array = [
{
  date: '2016-05-02',
  name: 'Ethan',
  status: 'success',
  total: '81'
},
{
  date: '2016-05-04',
  name: 'Lynn',
  status: 'fail',
  tag: '50'
},
{
  date: '2016-05-01',
  name: 'Kevin',
  status: 'success',
  tag: '20'
}];
let filterStatus = "success";
let filterNames = ['Lynn', 'Kevin'];
let result = array.filter((a,i)=>{
    return ( a.status === filterStatus && filterNames.some(f=>(f === a.name)) ) 
})
2017年4月20日 19:56
編輯回答
懶洋洋
let keys = Object.keys(filters)
let result = array.filter(item => {
  return keys.every(key => filters[key].indexOf(item[key]) !== -1)
})
2017年7月25日 10:48