Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
 }
})
like image 573
Colin Sygiel Avatar asked Dec 08 '22 17:12

Colin Sygiel


2 Answers

Try this :

array2.map(function(x){ 
       var result=array1.filter(a1=> a1.id==x.id);
       if(result.length>0) { x.name=result[0].name;}
       return x })
like image 152
Jaydip Jadhav Avatar answered Dec 10 '22 06:12

Jaydip Jadhav


Loop through each element and compare there ids. If they match update the name:

for (var i = 0; i < array2.length; i++) {
  for (var k = 0; k < array1.length; k++) {
    if (array2[i].id == array1[k].id) {
      array2[i].name = array1[k].name;
      break;
    }
  }
}

Try it:

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'
  }
]
console.log(array2);
for (var i = 0; i < array2.length; i++) {
  for (var k = 0; k < array1.length; k++) {
    if (array2[i].id == array1[k].id) {
      array2[i].name = array1[k].name;
      break;
    }
  }
}
console.log(array2);
like image 36
Alexander Higgins Avatar answered Dec 10 '22 06:12

Alexander Higgins