如何通过循环更新对象项

时间:2017-07-13 12:37:56

标签: node.js object async.js

我尝试向对象添加属性。我有一个客户列表,我想为每个客户添加一个包含邮件的数组,并发送给该客户。

但我无法将其添加到现有对象中。我做错了什么?

crmuser.find().exec(function(err, crmusers){
    console.log(crmusers);

    //LOG result
    [ { _id: 59563a7181438f4db8193379,
       emailName: 'Donald Duck',
       shop: 'dd',
       moreproperties: '',
       email: 'donald@duck.com',
    } ]

    async.each(Object.keys(crmusers), function(key, callback){
      mailService.getLogs({to: crmusers[key].email, typeMail: "CRM"}, function(err, result){
        console.log("res", result); // here we have the result from the mailService.getLogs() function


        crmusers[key]["sendMail"] = {result}; //Here I try to add a new property to the object

        console.log("USERR", crmusers[key]); // And here I can see that the property is not added
        callback();
      })
    }, function(){
      status = 200;
      response = {message: 'OK', crmusers};
      return res.status(status).json(response);
    })
})

1 个答案:

答案 0 :(得分:0)

您可以使用each函数从用户数组中的每个项目返回一个新对象,而不是使用forEachmap来迭代值。因为你是用户变量是一个对象而不是数组,所以最好的异步方法是mapValues

const users = {
 john: { email: 'test@test.com' },
 anne: { email: 'test@test.com' }
};

async.mapValues(users, function (user, key, callback) {
  mailService.getLogs({to: user.email, typeMail: "CRM"}, function(err, result){
    if (err) callback(err);
    user["sendMail"] = result;
    callback(null, user);
  })
}, function(err, result) {
    // result is now a new map of your users
    // {
    //   john: { sendMail: 'result', email: 'test@test.com' },
    //   anne: { sendMail: 'result', email: 'test@test.com' }
    // };
});