仅当键匹配时才合并 2 个对象数组
Merge 2 array of objects only if key matches
我有 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
对象的字段覆盖
我有 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
对象的字段覆盖