I have 2 arrays of
EL objects first named data :
const data = [
{
id: 1,
nombre: 'Piero',
},
{
id: 4,
nombre: 'Nelson',
},
{
id: 7,
nombre: 'Diego'
},
]
and the second called subs :
const subs = [
{
id: 1,
name: 'Temprano',
},
{
id: 4,
name: 'A tiempo',
},
{
id: 7,
name: 'Tarde'
},
]
In which I want to compare that if they have the same id the subs array passes their name and if it does not match that they put a data'-'
array try this way:
data.forEach((d)=>{
subs.forEach((s)=>{
if(d.id === s.id){
d.subname = s.name;
}
else {
d.subname = '-';
}
});
});
But it always prints me the values with '-'
as if it doesn't match any. What part am I doing wrong? Is there another easier way to do this? I would greatly appreciate your help.
The size of the subs array can vary
What happens is the following:
In the first iteration of the foreach data, it
id = 1
asks for each of the items, and finds that there is a match, so it assigns "Early" to Piero's subname; After looping through the others and finding no matches, he starts looping again withid = 4
What's happening?
and so on for each item, in the last iteration, we can see how Diego was correctly assigned, since he did not enter again and did not replace the correct value assigned in the previous iteration
Taking FederHico's comment into account, I solved it this way:
:D