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.
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
Asked: 2022-03-19 11:00:00 +0000
Seen: 7 times
Last updated: Nov 18 '22
Is it possible to not get any results when using Strings.Instr or IndexOf to search for a substring?
What is the method to obtain a hard copy of the outcome from a Google search?
How do I search for the first date (out of two) in file names using re?
How can I search for a portion of a word using django-elasticsearch-dsl-drf?
How can I achieve a successful batch search and replace using regular expressions?
What is the specific name to search for using cypress and react in order to click a button?