Dan Dan - 1 month ago 5
Javascript Question

Compare two arrays of objects and add a new attribute to the object that is matched

I have two arrays of objects like this:

let data1 = [ { userid_b: 'dan12345' }, { userid_b: 'emma12345' } ]
let data2 =[
{ username: 'dan', userid: 'dan12345' },
{ username: 'johndoe', userid: 'john12345' },
{ username: 'emma', userid: 'emma12345' },
{ username: 'Bob', userid: 'bob12345' },
{ username: 'Sam', userid: 'sam12345' }
]


I want to compare these two of
userid_b
and
userid
, and if they are same, I want to add a new attribute to
data2
.

So I want the result like this:

let data2 =[
{ username: 'dan', userid: 'dan12345', newAttribute: true },
{ username: 'johndoe', userid: 'john12345' },
{ username: 'emma', userid: 'emma12345', newAttribute: true },
{ username: 'Bob', userid: 'bob12345' },
{ username: 'Sam', userid: 'sam12345' }
]


How can I achieve this?

Answer

Loop both arrays and compare the values, making the assignment if necessary:

var data1 = [
  { userid_b: 'dan12345' },
  { userid_b: 'emma12345' }
];

var data2 = [ 
  { username: 'dan', userid: 'dan12345' },
  { username: 'johndoe', userid: 'john12345' },
  { username: 'emma', userid: 'emma12345' },
  { username: 'Bob', userid: 'bob12345' },
  { username: 'Sam', userid: 'sam12345' } 
];

// Loop the main array
for (var i = 0; i < data2.length; i++) {
  // Loop the second array
  for (var j = 0; j < data1.length; j++) {
    // If the user id matches
    if (data2[i].userid == data1[j].userid_b) {
      // Add the attribute
      data2[i].newAttribute = true;
      // Break out of the the 'j' loop to stop unnecessary iterations
      break;
    }
  }
}

console.log(data2);