I'm working on angular project using Typescript and I have the following array1:
array1: any = [
{
'garantie': 'A',
'checked': false
},
{
'garantie': 'B',
'checked': false
},
{
'garantie': 'C',
'checked': false
},
{
'garantie': 'D',
'checked': false
},
{
'garantie': 'E',
'checked': false
},
{
'garantie': 'F',
'checked': false
}
];
and i have another array that contains same json object structure , this is the code :
array2: any = [
{
'garantie': 'A',
'checked': true
},
{
'garantie': 'D',
'checked': true
},
{
'garantie': 'F',
'checked': true
}
];
my issue is I want to update the checked property of the second array based on guarantee property, this the result that I want:
[
{
'garantie': 'A',
'checked': true
},
{
'garantie': 'B',
'checked': false
},
{
'garantie': 'C',
'checked': false
},
{
'garantie': 'D',
'checked': true
},
{
'garantie': 'E',
'checked': false
},
{
'garantie': 'F',
'checked': true
}
];
i try this code but dosen't work :
for (let i = 0; i < 6; i++) {
if (this.array1[i] !== undefined && this.array2[i] !== undefined) {
if (this.array1[i].garantie === this.array2[i].garantie) {
this.array1[i].checked = this.array2[i].checked;
}
}
}
please do you have any suggestion on how to achieve this ?
Thanks in advance.
A, will not work for the second index and so on. You should be attempting afindin the second array to find the matching element from the first array. If a match is found, then update. Also, dont hardcode that loop counter, usearray1.lengthlet matchingObj = array2.find(a => a.garantie === array1[i].garantie); if (matchingObj) { do stuff }