I’e an array of objects that I want to get information (emails) from and store to a new array from.
I’ve tried several times but can’t quite get this to work.
My most recent attempt is:
function getAllCustomerEmails(data) {
let emailArray = [];
for (let i = 0; i < data.length; i++) {
return data[i].email;
}
}
What else do I need to do/what am I doing wrong here?
I was able to get all the emails to appear with a console log but can’t quite get it to return as a string or get it saved to the array.
4
Answers
You weren’t pushing anything to your array, you have to push
email
values to your array while inside the loop and return the array once after the loop has finished.Note: I’m using a mock array of objects here since I don’t know how your array looks like.
Another option using
.map()
Here, i have given an hardcoded array of object according to your need and then looped it and used push() method of array to add elements into it.
So, i have added all the emails from the respective objects and returned the new array.
try this.
or
You are returning the first object in the list your are looping through instead of pushing (adding) each item in to your email array and then return the email array. So the function will end on the first object instead of when the list has be loop through. I will try to demonstrate.
This is your array of objects:
So a array with objects that all contains a list (email).
Each time that you your are looping through list you wanna access that list.
At 0 you wanna get [email protected] etc.
When you are doing this:
You are saying only return the first element and when you have done that end the loop. So the first element in the list will be obj with [[email protected]]. With the index 0. And then the loop will end.
So what do we need to change or add?
We know that the condition is right but we wanna return a list of element and not only one like we are doing now. So we need to add something or push the each item in the list. Emailarray list.
And to do that:
Which means that each time the index increase and point on a "new item" in the array then we will "go in that object" so we can access the email and then add it to the email list.
First time [[email protected]]
Second time [[email protected]]
Third time [[email protected]]
Then when the loop is done will we return the array with emails: