I have a mern app and get all albums via axios.
the structure is like :
[
{
title: "",
artist: "",
reviews: [
{
username: "",
comment: "",
},
{
username: "",
comment: "",
},
]
},
{
title: "",
artist: "",
reviews: []
},
]
I need to filter every review.object that has a specific username inside for example BUT return the object which has that review array inside.
if index[3] res.data -> reviews -> object has username return that res.data object. I tried with filter inside filter but it did not work.
You can create a function that gets the username, then map and filter it so you can display only the datas you need
Try this
const datas = [
{
title: "",
artist: "",
reviews: [
{
username: "a",
comment: "",
},
{
username: "b",
comment: "",
},
]
},
{
title: "",
artist: "",
reviews: []
},
]
const filteredReviews = username => {
return datas.map(data => {
if (data.reviews.length > 0) {
if (data.reviews.filter(review => review.username == username).length > 0) {
return data
}
}
return null
}).filter(data => data)
}
by this example, I returned null inside the map for those object that I don't need, then filter the array for it's element that has a value
Then you can get the object you need by calling that function like this
console.log(filteredReviews('b'))