简体   繁体   中英

Javascript array filter with or clause

I have an array of object like this:

[
  {
    manufacturer: 'LG',
    diagonal: '32',
    resolution: '1080p'
  },
  {
    manufacturer: 'LG',
    diagonal: '24',
    resolution: '1080p'
  },
  {
    manufacturer: 'Samsung',
    diagonal: '32',
    resolution: '4k'
  },
  {
    manufacturer: 'Samsung',
    diagonal: '27',
    resolution: '1080p'
  },
]

If the filter has each property once {'manufacturer':'LG', 'diagonal':'27'} I can filter it like this newarray = myarray.filter((item) => {return item['manufacturer']=='LG' && item['diagonal']=='32'})

But how can I filter it, if the filter has each property multiple times?

{'manufacturer':'Samsung', 'manufacturer':'LG', 'diagonal':'32'}

I need something to work for bigger filters, not only for this particular case.

Use Array.some() method.

 const myarray = [ { manufacturer: 'LG', diagonal: '32', resolution: '1080p' }, { manufacturer: 'LG', diagonal: '24', resolution: '1080p' }, { manufacturer: 'Samsung', diagonal: '32', resolution: '4k' }, { manufacturer: 'Samsung', diagonal: '27', resolution: '1080p' }, ] const newarray = myarray.filter((item) => { return ["LG", "Samsung"].some((val) => item.manufacturer === val) && item.diagonal=='32' }); console.log(newarray)

Do you mean you want to filter for multiple values? Something like:

newarray = myarray.filter((item) => {
    return ( item['manufacturer'] === 'LG' ||item['manufacturer'] === 'Samsung' ) 
             && item['diagonal'] === '32'} )

Or you could have a list of possible values and use Array.includes()

const manufacturerToSearchFor = ['Samsung', 'LG'];

newarray = myarray.filter((item) => {
        return ( manufacturerToSearchFor.includes(item['manufacturer'])
                 && item['diagonal'] === '32'} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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