How can I compare two arrays of objects and change a value for those that are found in both arrays?

Viewed 14016

Let's say I have two arrays of objects:

let array1 = [
          {
           id: 1,
           name: 'snow'
          },
          {
           id: 4,
           name: 'jo'
          },
          {
           id: 8,
           name: 'bran'
          },
          {
           id: 12,
           name: 'gondo'
          },
          {
           id: 13,
           name: 'peter'
          }
        ]

let array2 = [
      {
       id: 3,
       name: 'brim'
      },
      {
       id: 4,
       name: 'not-jo'
      },
      {
       id: 8,
       name: 'not-bran'
      },
      {
       id: 13,
       name: 'spleen'
      }
    ]

I want to find all the objects in array2 that match by id with array1, and change their name values to match the name values in array1.

In my pseudocode:

array1.forEach((person)=> {
 if(person.id is equal to person.id in array2){
   person.name = person.name in array1
 }
})
5 Answers

array2.filter(o => array1.find(o2 => o.id === o2.id))

Related