简体   繁体   English

按多个值过滤对象数组

[英]Filter array of objects by multiple values

I want to be able to create a new array of objects by filtering one by multiple search terms 我希望能够通过多个搜索词过滤一个对象来创建新的对象数组

Example: 例:

  const arr = [
  {
      'city': 'Atlanta',
      'state': 'Georgia'
  },
  {
      'city': 'Chicago',
      'state': 'Illinois'
  },
  {
      'city': 'Miami',
      'state': 'Florida'
  }
]

const searchTerms = ['Georgia', 'Florida']

I would like to be able to filter it like this: 我希望能够像这样过滤它:

arr.filter(obj => obj['state'].includes(searchTerms))

I've found that entering one string with the .includes works, but not an array. 我发现使用.includes输入一个字符串是可行的,但不能使用数组。 I'm open to different logic or even a third party library like lodash or something. 我愿意接受不同的逻辑,甚至可以接受lodash之类的第三方库。 I would like to return a new array of objects with only the states that are in the searchterms array 我想返回一个仅包含searchterms数组中状态的对象新数组

You should call searchTerms.includes on obj.state and not the other way around. 你应该叫searchTerms.includesobj.state ,而不是周围的其他方式。 So it becomes: 这样就变成了:

let result = arr.filter(obj => searchTerms.includes(obj.state));

Which means filter out objects that have thier state property included in the array searchItems . 这意味着筛选出具有state属性包含在数组searchItems中的searchItems

Example: 例:

 const arr = [{'city': 'Atlanta', 'state': 'Georgia'}, {'city': 'Chicago', 'state': 'Illinois'}, {'city': 'Miami', 'state': 'Florida'}]; const searchTerms = ['Georgia', 'Florida']; let result = arr.filter(obj => searchTerms.includes(obj.state)); console.log(result); 

If you're interested in a solution using Ramda : 如果您对使用Ramda的解决方案感兴趣:

 const cities = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': 'Chicago', 'state': 'Illinois' }, { 'city': 'Miami', 'state': 'Florida' } ]; const findCities = (search, cities) => { const predicate = R.flip(R.includes)(search); return R.filter(R.compose(predicate, R.prop('state')), cities); }; console.log( findCities(['Georgia', 'Florida'], cities) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> 

Another approach you could take here is to utilize Map which would have consistent retrieval times: 您可以在此处采取的另一种方法是利用Map ,该Map检索时间将保持一致:

 const arr = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': 'Chicago', 'state': 'Illinois' }, { 'city': 'Miami', 'state': 'Florida' } ] const searchTerms = ['Georgia', 'Florida'] const searchMap = arr.reduce((r,c) => (r.set(c.state, c),r), new Map()) console.log(searchTerms.map(x => searchMap.get(x))) 

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

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