I’m trying to send multiple items to multiple contacts in my contacts list , I use nested loop but it only send the last item for each contact ignoring the rest of the items , I didn’t know what I’m doing wrong.
here are my arrays :
ContactList = ['john','jem'];
itemList = [
{
"ItemTo": 'jhon@gmail.com',
"ItemType": 'type1'
},
{
"ItemTo": 'jem@gmail.com',
"ItemType": 'type2'
}
]
here is my JS code :
onClick() {
for (let i = 0; i < this.ContactList.length; i++) {
for (let j=0; j<this.itemList; j++){
let messageToSend = this.extractMessageDetails(
this.ContactList[i],
this.itemList[j]
);
}
}
}
extractMessageDetails(contact, item) {
const ItemTo = contact.contactId;
const ItemType = item.type;
const itemToSend = {
"ItemTo": ItemTo,
"ItemType": ItemType
}
return itemToSend;
}
Advertisement
Answer
Create an array messagesToSend = [] outside the second loop and then inside the 2nd loop push your object in that variable messagesToSend.push(this.extractMessageDetails(this.ContactList[i], this.itemList[j]););. So in the end of your second loop you will have messages for each contact
for (let i = 0; i < this.ContactList.length; i++) {
let messagesToSend = [];
for (let j = 0; j < this.itemList; j++) {
messagesToSend.push(
this.extractMessageDetails(this.ContactList[i], this.itemList[j]););
}
///send messages to contract[i]
}
If you want to collect all messages for all contracts move declaration of array outside the loops