2017-06-12 36 views
0

一個監聽更改的Firebase事件。Firebase函數 - 循環事件值

exports.sendTestEmail = functions.database.ref('/email/{pushID}') 
    .onWrite(event => { 

    // Only edit data when it is first created. 
    if (event.data.previous.exists()) { 
     return; 
    } 
    // Exit when the data is deleted. 
    if (!event.data.exists()) { 
     return; 
    } 

    return sendTestEmail(event); 
    }); 

function sendTestEmail(email, event) { 

    const users = event.data.val(); 
    console.log(users); 

    }); 
} 

這是結果的執行console.log(用戶):

{ '-Km8VHEPHExBtpIN_7q0': 
    { admin: 'false', 
    birthday: '76', 
    description: 'desc', 
    email: '[email protected]', 
    first_name: 'fname', 
    last_name: 'lname', 
    level: 5, 
    occupation: 'dev', 
    occupationLevel: 'dev5', 
    phone: '+8766', 
    verified: false }, 
    '-KmSjAaxdCUvrPEQ8InI': 
    { admin: 'false', 
    birthday: '1990', 
    description: 'desc', 
    email: '[email protected]', 
    first_name: 'fname', 
    last_name: 'lanam3', 
    level: 4, 
    occupation: 'dev', 
    occupationLevel: 'dev4', 
    phone: '+23434', 
    verified: false } } 

似乎不是我能循環,並得到所需要用來發送電子郵件到誰擁有電子郵件地址的用戶的電子郵件。

+0

請嘗試在此處查看此問題。 https://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members你有一個普通的舊json對象,爲什麼不只是循環通過。 –

回答

0

也許考慮這樣的事情。

function sendTestEmail(event) { 
    emails = []; // create empty email array 
    const users = event.data.val(); // get users, as you currently were. 
    for (var key in users) { // loop through users to retrieve key. 
     var email = users[key].email; // get email using key 
     emails.push(email); // push to emails array 
    } 
    return emails; 
}