我有两个数组:
第一个阵列:
generalInfo = [{"fName": "Suku", "lName": "Brown", "sex": "Male", "Id": "RY12S"}, {"fName": "Mary", "lName": "Sue", "sex": "Female", "Id": "UT72W"}]
第二阵列:
paymentInfo = [{"Id": "RY12S", "amount": "1000.00", "purpose": "rent", "date": "2017-17-07"}, {"Id": "UT72W", "amount": "5000.00", "purpose": "renovation", "date": "2017-15-07"}]
现在,我希望能够比较两个数组的Id字段并返回它们的唯一信息。
至少第三个应该是这样的:
specificInfo = [{"Id": "RY12S","fName": "Suku", "lName": "Brown", "amount": "1000.00", "purpose": "rent"}, {"Id": "UT72W","fName": "Mary", "lName": "Sue", "amount": "5000.00", "purpose": "renovation"}]
有没有简单的方法来实现这个目标?
答案 0 :(得分:0)
var generalInfo = [{"fName": "Suku", "lName": "Brown", "sex": "Male", "Id": "RY12S"}, {"fName": "Mary", "lName": "Sue", "sex": "Female", "Id": "UT72W"}];
var paymentInfo = [{"Id": "RY12S", "amount": "1000.00", "purpose": "rent", "date": "2017-17-07"}, {"Id": "UT72W", "amount": "5000.00", "purpose": "renovation", "date": "2017-15-07"}];
var uniqueInfo = generalInfo.map((generalItem) => {
var paymentItem = paymentInfo.find((item) => item.Id === generalItem.Id);
return {
Id: generalItem.Id,
fName: generalItem.fName,
lName: generalItem.lName,
amount: paymentItem.amount,
purpose: paymentItem.purpose
};
});
console.log(uniqueInfo);

尝试理解这背后的逻辑,如果你需要在ES5中实现,请在发布之前自己尝试。