Compare 2 fixes and assign matching value

4

I have 2 arrangements of objects
The first one called data :

const data = [
  {
    id: 1,
    nombre: 'Piero',
  },
  {
    id: 4,
    nombre: 'Nelson',
  },
  {
    id: 7,
    nombre: 'Diego'
  },
 ]

and the second one 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 arrangement will pass your name and if it does not match that you put a '-' to the array > data try this way:

data.forEach((d)=>{
 subs.forEach((s)=>{
   if(d.id === s.id){
     d.subname = s.name;
   }
   else {
     d.subname = '-';
    }
   });
 }); 

But I always print the values with '-' as if it did not match any. What part am I doing wrong? Is there another, simpler way to do this? I would greatly appreciate your help.

The size of the subs fix may vary

    
asked by Piero Pajares 11.05.2018 в 21:27
source

2 answers

1

Taking into account FederHico's comment, I solved it this way:

data.forEach(d => {
  const match = subs.find(s => s.id === d.id);
   d.subname = match ? match.name : '-';
});

: D

    
answered by 12.05.2018 / 02:20
source
1

What happens is the following:

In the first iteration of the foreach data, enter id = 1 question for each of the items, and find that there is a match, for which, assign "Early" to the subname of Piero; After touring the others and not finding matches, start walking again with id = 4

What's up?

  

That in the first iteration of subs with id=4 finds that id = 4 != id = 1 whereby, overwrites the   "Early" value that was assigned correctly by "-"

and so on for each item, in the last iteration, we can see how Diego was correctly assigned, since he did not re-enter and did not replace the correct value assigned in the previous iteration

    
answered by 11.05.2018 в 22:40