Home > Software engineering >  Merge 2 array of objects only if key matches
Merge 2 array of objects only if key matches

Time:06-03

I have 2 array of objects which I want to merge their properties together ONLY IF user from both array matches.

Example Arrays

arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0 }];
arr2 = [{ user: 'fred', gender: 'male', age: 27, state: "arizona" }, { user: 'john',gender: 'male', age: 28, state: "texas" }];

Expected Output

arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0, gender: 'male', age: 27, state: "arizona" }];

Here's what I tried so far, but it is returning an empty array

var result = [];
arr1.concat(arr2)
  .forEach(item =>
    result[item.user] =
    Object.assign({}, result[item.user], item)
  );
result = result.filter(r => r);
console.log(result)

CodePudding user response:

You can achieve taht by using map, filter Array functionalities and spread operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):

const arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0 }, { user: 'john2',gender: 'male', age: 28, state: "texas" }];
const arr2 = [{ user: 'fred', gender: 'male', age: 27, state: "arizona" }, { user: 'john',gender: 'male', age: 28, state: "texas" }];
const newArray = arr1.map((obj) => {
  const secondArrayObj = arr2.find((obj2) => obj2.user === obj.user);
  if (secondArrayObj) {
    return {...secondArrayObj, ...obj}
  }
  return null;
}).filter((obj) => obj != null);
console.log(newArray); 
//[{
//  "user": "fred",
//  "gender": "male",
//  "age": 27,
//  "state": "arizona",
//  "bank": 1,
//  "depositAmount": 100,
//  "withdrawalAmount": 0
//}] 

Notice that if you have same field in both objects, field from arr2 object will be overridden by field from arr1 object

  • Related