如何比较数组的对象并在javascript中返回唯一数组

时间:2017-07-17 10:51:10

标签: javascript arrays

我有两个数组:

第一个阵列:

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"}]

有没有简单的方法来实现这个目标?

1 个答案:

答案 0 :(得分:0)

包含mapfind的ES6解决方案:



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中实现,请在发布之前自己尝试。