最近,当我尝试从多循环语句返回数据时,我陷入了循环陷阱。
我正在创建个人资料过滤系统,该系统在获取人员后。它将过滤用户的好友。
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}
];
谢谢。
最佳答案
正如 @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
})
}
关于javascript - 使用 javascript 循环有效返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49173981/