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 :
JavaScript
x
14
14
1
ContactList = ['john','jem'];
2
3
itemList = [
4
{
5
"ItemTo": 'jhon@gmail.com',
6
"ItemType": 'type1'
7
},
8
9
{
10
"ItemTo": 'jem@gmail.com',
11
"ItemType": 'type2'
12
}
13
]
14
here is my JS code :
JavaScript
1
24
24
1
onClick() {
2
for (let i = 0; i < this.ContactList.length; i++) {
3
for (let j=0; j<this.itemList; j++){
4
let messageToSend = this.extractMessageDetails(
5
this.ContactList[i],
6
this.itemList[j]
7
);
8
}
9
}
10
}
11
12
extractMessageDetails(contact, item) {
13
14
const ItemTo = contact.contactId;
15
const ItemType = item.type;
16
17
const itemToSend = {
18
"ItemTo": ItemTo,
19
"ItemType": ItemType
20
}
21
22
return itemToSend;
23
}
24
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
JavaScript
1
9
1
for (let i = 0; i < this.ContactList.length; i++) {
2
let messagesToSend = [];
3
for (let j = 0; j < this.itemList; j++) {
4
messagesToSend.push(
5
this.extractMessageDetails(this.ContactList[i], this.itemList[j]););
6
}
7
///send messages to contract[i]
8
}
9
If you want to collect all messages for all contracts move declaration of array outside the loops