I have an object that holds some email addresses in a component. I want to pass that object to a service that I have, and store all the values that have the email key in a variable.
here is the object that I have
mEmails = [
{
id: 1,
email: ''
},
{
id: 2,
email: ''
},
{
id: 3,
email: ''
},
{
id: 4,
email: ''
}
];
saveEmails(form: NgForm) {
this.mEmails[0].email = form.value[1];
this.mEmails[1].email = form.value[2];
this.mEmails[2].email = form.value[3];
this.mEmails[3].email = form.value[4];
console.log(this.mEmails);
this.sessionService.emails.emit(this.mEmails);
}
Now I retrieve the array in my Service like this.
this.emails.subscribe(
emails => {
console.log(emails);
});
the result is
0: Object { id: 1, email: "[email protected]" }
1: Object { id: 2, email: "[email protected]" }
2: Object { id: 3, email: "[email protected]" }
3: Object { id: 4, email: "[email protected]" }
Now I get the array but the desired result that I would like is for me to get the values in a variable that looks like this
const emails = ['[email protected]','[email protected]','[email protected]','[email protected]']
I could do this manually but getting the index and setting that to a variable but that is very ineficeient and no a great way to scale up in the future. I am looking for something that will sort through the array and the object and return all the values with the key 'email' and concat them together and join them with a ','
Use the Array.map
function:
let mEmails = [
{
id: 1,
email: '[email protected]'
},
{
id: 2,
email: '[email protected]'
},
{
id: 3,
email: '[email protected]'
},
{
id: 4,
email: '[email protected]'
}
];
console.log(mEmails.map(obj => obj.email))