0

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)

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.