简体   繁体   中英

How to Filter an Array of Object and check if Specific key has a value in an Array

I have this Array of Objects:

const Books = [
  {title:'Book 1', Date: '12/12/2000'},
  {title:'Book 2', Date: '12/12/2001'},
  {title:'Book 3', Date: '12/12/2003'},
  {title:'Book 4', Date: '12/12/2003'}
]

I have this Array of selected Books:

 const selectedBooks = ['Book1','Book4']

Is it possible to obtain a result of:

 const filteredBooks = [
     {title:'Book 1', Date: '12/12/2000'},
     {title:'Book 4', Date: '12/12/2003'}
 ]

Is there a method in lodash or ES6 to implement it?

You can use Array.prototype.filter with Array.prototype.includes :

 const Books = [ { title: 'Book 1', Date: '12/12/2000' }, { title: 'Book 2', Date: '12/12/2001' }, { title: 'Book 3', Date: '12/12/2003' }, { title: 'Book 4', Date: '12/12/2003' } ] const selectedBooks = ['Book 1', 'Book 4'] const filteredBooks = Books.filter(book => selectedBooks.includes(book.title)); console.log(filteredBooks);

You can filter for all the elements for which selectedBooks includes their title :

const filteredBooks = Books.filter(book => selectedBooks.includes(book.title))

filter returns all entries for which the given callback returns a truthy value, and includes will tell you whether the array contains the given value.

Yes, try array filter operator

const filteredBooks = Books.filter(({title}) => selectedBooks.includes(title))

I'm assuming the items in selectedBooks will match the title in filteredBooks . If not, you'll need some way to map those values.

You want a combination of Array.prototype.filter and Array.prototype.indexOf .

const filteredBooks = Books.filter(book => selectedBooks.indexOf(book.title) !== -1)

 const books = [ { title: 'Book 1', Date: '12/12/2000' }, { title: 'Book 2', Date: '12/12/2001' }, { title: 'Book 3', Date: '12/12/2003' }, { title: 'Book 4', Date: '12/12/2003' } ]; const selectedBooks = ['Book 1', 'Book 4']; const filteredBooks = _.filter(books, book => _.includes(selectedBooks, book.title)); console.log(filteredBooks);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

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