2017-10-17 54 views
1

對象的兩個數組在MySQL中,如果我有兩個表是這樣的:加入物業

appointments 

appointment_id patient_id appointment_time 
------------------------------------------------------- 
1     42   2017-10-17 08:00:00 
2     43   2017-10-17 08:30:00 

patients 

patient_id name 
--------------------------- 
42   Joe Smith 
43   Sally Sue 
44   Jim Bob 

那麼我可以離開連接兩個表這樣

SELECT * 
FROM appointments 
LEFT JOIN patients ON appointments.patient_id = patients.patient_id 

我會得到這樣的結果:

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 

所以我的問題是,在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' 
    } 
]; 

const patients = [ 
    { 
    patientId: 42, 
    name: 'Joe Smith' 
    }, 
    { 
    patientId: 43, 
    name: 'Sally Sue' 
    }, 
    { 
    patientId: 44, 
    name: 'Jim Bob' 
    } 
]; 

我怎麼能離開加盟患者陣列到基於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' 
    } 
] 

我知道,有一個在lodash的unionBy方法,但將刪除約會對象的屬性。

回答

2

執行以下操作:

let result = appointments.map(a => ({...patients.find(p => a.patientId === p.patientId), ...a})); 
+0

,而不是'名稱:p.name'末,你可以使用'... p'病人的所有道具合併。 –

+0

@BrianGlaz當然!我已經改變了答案,謝謝 – dhilt

+0

我會傾向於交換'病人'和'約會',所以結果是1:1映射到約會的問題問:p –