[英]Filter an Array of Objects inside an Array of Objects
I have a mern app and get all albums via axios.我有一个 mern 应用程序,并通过 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.我需要过滤每条评论。object 里面有一个特定的用户名,例如但是返回 object 里面有这个评论数组。
if index[3] res.data -> reviews -> object has username return that res.data object.如果 index[3] res.data -> 评论 -> object 有用户名,则返回 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您可以创建一个获取用户名的 function,然后创建 map 并对其进行过滤,以便仅显示您需要的数据
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通过这个例子,我在 map 中为那些我不需要的 object 返回了
null
Then you can get the object you need by calling that function like this然后你可以通过像这样调用 function 来获得你需要的 object
console.log(filteredReviews('b'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.