当我尝试从多循环语句中返回数据时,我最近陷入了一个循环坑。
我正在创建配置文件过滤系统,在获取人员之后。它将过滤用户的朋友。
class UserFriend {
analyseUserFriends(people, userfriends){
people.forEach(person => {
this.userfriends.forEach(friend => {
if(person._id.toString() == friend._id.toString()){
person.relationship = 0
}else{
person.relationship = 1;
}
return friend;//After loging friend the object of relationship is part of the member
});
return person;//After loging person the object of relationship is not part of the member
});
}
}
数据来自Mongo,与此类似
userfriends:[
{friend: mongoId},
{friend: mongoId},
{friend: mongoId},
{friend: mongoId},
];
people: [
{_id: mongoId},
{_id: mongoId},
{_id: mongoId},
{_id: mongoId},
{_id: mongoId},
{_id: mongoId},
{_id: mongoId},
{_id: mongoId}
];
感谢。
答案 0 :(得分:1)
正如@Leafyshark在评论中提到的,这是map
方法的用例。结合find
方法,您应该能够实现这一目标:
function analyseUserFriends (people, userFriends) {
return people.map(person => {
person.relationship = userFriends.find(x => x.friend.toString() === person._id.toString()) ? 1 : 0
return person
})
}