2017-07-13 21 views
0

我嘗試將屬性添加到對象。我有一個與客戶的名單,併爲每個客戶我想添加一個數組與郵件發送給該客戶。如何通過循環更新對象項目

但我不能將它添加到現有的對象。我做錯了什麼?

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

    //LOG result 
    [ { _id: 59563a7181438f4db8193379, 
     emailName: 'Donald Duck', 
     shop: 'dd', 
     moreproperties: '', 
     email: '[email protected]', 
    } ] 

    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); 
    }) 
}) 
+0

您可以登錄'err'並檢查是否有錯誤? – Sridhar

+0

你的代碼適合我。可能多個元素在數組中相同的ID? – Sridhar

回答

0

而是通過價值觀與each或迭代的forEach您可以使用map函數從每個項目中的用戶數組返回一個新的對象。當你的用戶變量是一個對象不是一個數組的最佳異步方法使用是mapValues

const users = { 
john: { email: '[email protected]' }, 
anne: { email: '[email protected]' } 
}; 

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: '[email protected]' }, 
    // anne: { sendMail: 'result', email: '[email protected]' } 
    // }; 
}); 
+0

謝謝!但是我得到一個'TypeError:Can not read property'符號(Symbol.toStringTag)',它的async.mapValues(crmusers),函數(user,key,callback){'crmusers是我們從貓鼬請求的對象。像'crmusers.find()。exec(函數(err,crmusers)' – NVO

+0

編輯我的問題與查找線和crmusers的結果 – NVO

+0

添加cmsusers對象的控制檯 – sidhuko