简体   繁体   中英

JavaScript push data to array

I'm new for javascript and try to push some data to the array as below.

async function mailSend(callback) {
User = [];
for (let scriptData of automatedScriptData.dataList) {
    let userData = {
        email: scriptData["Business Email"],
        password: "acc0unt@123",
        name: scriptData["First Name"] + " " + scriptData["Last Name"],
        firstName:scriptData["First Name"],
        title: scriptData["Title"],
        timeZone: scriptData["Time Zone"],
        location: scriptData["Country"],
        company: scriptData["Company"]
    };


    User.push(userData.firstName);
    console.log(User);

    }

}

My result as below.

[ 'Brock' ] [ 'Brock', 'Kristian' ]

But I want just [ 'Brock', 'Kristian' ]

Can anyone help me to solve that issue.

This is because you have added console.log(User); inside for loop. Move this out of the for loop you will get the desired output.

Try this:

async function mailSend(callback) {
User = [];
  for (let scriptData of automatedScriptData.dataList) {
    let userData = {
      email: scriptData["Business Email"],
      password: "acc0unt@123",
      name: scriptData["First Name"] + " " + scriptData["Last Name"],
      firstName:scriptData["First Name"],
      title: scriptData["Title"],
      timeZone: scriptData["Time Zone"],
      location: scriptData["Country"],
      company: scriptData["Company"]
    };    
    User.push(userData.firstName);
  }    
}
console.log(User);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM