javascript - 使用 javascript 循环有效返回数据

标签 javascript mongodb

最近,当我尝试从多循环语句返回数据时,我陷入了循环陷阱。

我正在创建个人资料过滤系统,该系统在获取人员后。它将过滤用户的好友。

 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/

相关文章:

java - 使用 Tasklet 在 Spring Batch 中或在 CompositeItemWriter 中创建逻辑?

python - 如何改进 XML 导入到 mongodb 中?

mongodb - 删除 MongoDB 集合中的数据但保留索引的更好方法

javascript - 使 intlTelInput 和 Jquery 掩码插件协同工作

javascript - 是否有任何工具可以显示源代码,即使 dom 是由 Javascript 生成的

mongodb - 在 JavaEE Web 服务中使用单个 MongoClient

node.js - MongoDB全文搜索和按相关性排序的多个单词

javascript - 有渲染 2d 键盘的 JavaScript 库吗?

javascript - 如何使用 MySQL 登录 ReactJS、NodeJS?

javascript - 顺利直接移动到另一个div(过渡)