连接属性上的两个对象数组

Kyl*_*gan 2 javascript

在MySQL中,如果我有两个这样的表:

appointments

appointment_id    patient_id    appointment_time
-------------------------------------------------------
1                 42            2017-10-17 08:00:00
2                 43            2017-10-17 08:30:00
Run Code Online (Sandbox Code Playgroud)

patients

patient_id    name
---------------------------
42            Joe Smith
43            Sally Sue
44            Jim Bob
Run Code Online (Sandbox Code Playgroud)

然后我可以像这样离开两个表

SELECT *
FROM appointments
LEFT JOIN patients ON appointments.patient_id = patients.patient_id
Run Code Online (Sandbox Code Playgroud)

我会得到这样的结果:

appointment_id    patient_id    appointment_time       patient_id    name
----------------------------------------------------------------------------------
1                 42            2017-10-17 08:00:00    42            Joe Smith
2                 43            2017-10-17 08:30:00    43            Sally Sue
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,在Javascript(ES6 +)中,如果我有两个这样的对象数组:

const appointments = [
  {
    appointmentId: 1,
    patientId: 42,
    appointmentTime: '2017-10-17 08:00:00'
  },
  {
    appointmentId: 2,
    patientId: 43,
    appointmentTime: '2017-10-17 08:30:00'
  }
];
Run Code Online (Sandbox Code Playgroud)

const patients = [
  {
    patientId: 42,
    name: 'Joe Smith'
  },
  {
    patientId: 43,
    name: 'Sally Sue'
  },
  {
    patientId: 44,
    name: 'Jim Bob'
  }
];
Run Code Online (Sandbox Code Playgroud)

我如何基于该patientId属性将患者数组加入约会数组?

[
  {
    appointmentId: 1,
    patientId: 42,
    appointmentTime: '2017-10-17 08:00:00',
    name: 'Joe Smith'
  },
  {
    appointmentId: 2,
    patientId: 43,
    appointmentTime: '2017-10-17 08:30:00',
    name: 'Sally Sue'
  }
]
Run Code Online (Sandbox Code Playgroud)

我知道unionBylodash 中有该方法,但是它将删除约会对象中的属性。

dhi*_*ilt 5

请执行以下操作:

let result = appointments.map(a => ({...patients.find(p => a.patientId === p.patientId), ...a}));
Run Code Online (Sandbox Code Playgroud)