Ask Your Question
4

How can you search for an object that has a property matching a specific value within a nested array?

asked 2022-03-19 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-11-18 10:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-19 11:00:00 +0000

Seen: 16 times

Last updated: Nov 18 '22