Let's say I have an array structured like this:
const arr = [
{
id: '123',
book: {isNew: true}
},
{
id: '123',
book: {isNew: false}
},
{
id: '123',
book: {isNew: false}
},
{
id: '123',
book: {isNew: true}
},
]
My goal is to filter the array and only retrieve objects where the book object has isNew set to true.
I initially tried the following approach:
arr.filter(obj => {
// Use a forEach loop to check for new books
}
However, since a forEach loop doesn't return any values, that method didn't work as expected.
UPDATE
It seems my explanation was somewhat unclear. In each object of the array, there can be multiple "Book" objects with dynamic keys. I want to identify objects that have at least one "Book" object with isNew set to true.
For example:
const arr = [
{
id: '123',
book1242: {isNew: true},
book9023: {isNew: false},
},
{
id: '123',
book0374: {isNew: false},
book9423: {isNew: false},
},
{
id: '123',
book8423: {isNew: false},
book9023: {isNew: false},
},
{
id: '123',
book6534: {isNew: true},
book9313: {isNew: false},
},
]
Thus, after filtering, my resulting array should contain the first and last elements from the original array.