Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To search for an object that has a property matching a specific value within a nested array, you can use the array method find() combined with the array method some() and the === (strict equality) operator.

For example, let's say you have an array of objects representing books, and each book has an array of authors:

const books = [
  {
    title: 'The Great Gatsby',
    authors: [
      { name: 'F. Scott Fitzgerald', nationality: 'American' },
      { name: 'Ernest Hemingway', nationality: 'American' }
    ]
  },
  {
    title: 'To Kill a Mockingbird',
    authors: [
      { name: 'Harper Lee', nationality: 'American' }
    ]
  },
  {
    title: '1984',
    authors: [
      { name: 'George Orwell', nationality: 'British' }
    ]
  }
]

To find the first book that has an author with the nationality "American", you can use the following code:

const bookWithAmericanAuthor = books.find((book) => {
  return book.authors.some((author) => {
    return author.nationality === 'American'
  })
})

console.log(bookWithAmericanAuthor) // returns "{ title: 'The Great Gatsby', authors: [ { name: 'F. Scott Fitzgerald', nationality: 'American' }, { name: 'Ernest Hemingway', nationality: 'American' } ] }"

This code first uses the find() method to search for a book that returns true for the given callback function, which checks if any of the authors in the book's authors array have the nationality property set to "American". It does this by using the some() method to iterate through each author in the array and checking if any of them satisfy the given condition. If a book with an American author is found, it is returned.