I am trying to update the array finalObject.members
by using values from another array called allParticipants
. The structure of the second array (allParticipants
) is as follows:
allParticipants = [
{
uid:"mem1_100_00",
member: "mem1",
tontine: "100"
total: 785
},
{
uid:"mem1_100_01",
member: "mem1",
tontine: "100"
total: 800
},
{
uid:"mem1_200_00",
member: "mem1",
tontine: "200"
total: 1000
},
{
uid:"mem2_100_00",
member: "mem2",
tontine: "100"
total: 200
},
{
uid:"mem2_200_00",
member: "mem2",
tontine: "200"
total: 7850
},
{
uid:"mem2_200_01",
member: "mem2",
tontine: "200"
total: 5000
},
{
uid:"mem2_200_02",
member: "mem2",
tontine: "200"
total: 1600
},
{
uid:"mem3_100_00",
member: "mem3",
tontine: "100"
total: 150
},
{
uid:"mem3_100_01",
member: "mem3",
tontine: "100"
total: 0
},
{
uid:"mem3_200_00",
member: "mem3",
tontine: "200"
total: 2500
}
]
The updated array (finalObject.members
) is expected to have the following structure after the updates:
finalObject.members = [
{
uid: "mem1",
tontines: {
100:[
{
uid: "mem1_100_00",
total:785
},
{
uid: "mem1_100_01",
total:800
},
],
200:[
{
uid: "mem1_200_00",
total:1000
}
]
}
},
{
uid: "mem2",
tontines: {
100: [
{
uid: "mem2_100_00",
total: 200
}
],
200:[
{
uid: "mem2_200_00",
total: 7850
},
{
uid: "mem2_200_01",
total: 5000
},
{
uid: "mem2_200_02",
total: 1600
}
]
}
},
{
uid: "mem3",
tontines: {
100: [
{
uid: "mem3_100_00",
total: 150
},
{
uid: "mem3_100_01",
total: 0
}
],
200:[
{
uid: "mem3_200_00",
total: 2500
}
]
}
}
]
The code I have written for this process is as follows:
const sizMem = finalObject.members.length;
const sizPartp = allParticipants.length;
for(let idx1=0; idx1<sizPartp; idx1++){
let partP = allParticipants[idx1]
for(let idx2=0; idx2<sizMem; idx2++){
let memP = finalObject.members[idx2];
if(partP.member.localeCompare(memP.uid) == 0){
finalObject.members[idx2].tontines[partP.tontine].push({
uid: partP.uid,
total: partP.total,
})
break
}
}
}
However, the output I am getting seems to be incorrect. It is adding all elements for each member instead of adding only the new element to the corresponding member. I have double-checked the if
conditions and everything seems to be correct. The insertion is only happening when the member
property of Participant
matches the uid
property of a member
. Yet, the new element is being added everywhere!
What could be the issue in my code?