我有2个对象数组,我想合并它们的属性,只有当user
从两个数组匹配。
例子数组
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" }];
预期输出
arr1 = [{ bank: 1, user: 'fred', depositAmount: 100, withdrawalAmount: 0, gender: 'male', age: 27, state: "arizona" }];
这是我到目前为止尝试的,但它返回一个空数组
var result = [];
arr1.concat(arr2)
.forEach(item =>
result[item.user] =
Object.assign({}, result[item.user], item)
);
result = result.filter(r => r);
console.log(result)
您可以通过使用map
,filter
数组功能和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
//}]
注意,如果两个对象中有相同的字段,arr2
对象中的字段将被arr1
对象中的字段覆盖