我有以下用例,我有两个数组,如下面的
arr1=[{room_no:1,bed_no:'1A'},
{room_no:1,bed_no:'1B'},
{room_no:2,bed_no:'2A'},
{room_no:3,bed_no:'3A'},
{room_no:3,bed_no:'3B'},
{room_no:4,bed_no:'4A'}]
arr2=[
{ patient_details:[{name:'patient1',age:22}],
patient_room_details:[{room_no:1,bed_no:'1A'}],
status:'occupied'
},
{ patient_room_details:[{room_no:1,bed_no:'1B'},
status:'available'
},
{ patient_details:[{name:'patient2',age:32}],
patient_room_details:[{room_no:2,bed_no:'2A'}],
status:'occupied'
}
{ patient_room_details:[{room_no:3,bed_no:'3A'},
status:'cleaning'
},
]
我试图比较第一个数组中的room_no和bed_no与第二个数组patient_room_details。如果找到匹配,则将匹配的对象推送到具有patient_details,patient_room_details和status的结果数组。如果找不到匹配项,我需要将状态仅推送为AVAILABLE。
我无法将状态推送为AVAILABLE,如果找不到匹配项,任何帮助都将不胜感激
,最终结果就像
result=[
{ patient_details:[{name:'patient1',age:22}],
patient_room_details:[{room_no:1,bed_no:'1A'}],
status:'occupied'
},
{ patient_room_details:[{room_no:1,bed_no:'1B'},
status:'available'
},
{ patient_details:[{name:'patient2',age:32}],
patient_room_details:[{room_no:2,bed_no:'2A'}],
status:'occupied'
},
{ patient_room_details:[{room_no:3,bed_no:'3A'},
status:'cleaning'
},
{ patient_room_details:[{room_no:3,bed_no:'3B'},
status:'available'
},
{ patient_room_details:[{room_no:4,bed_no:'4A'},
status:'available'
},
]
答案 0 :(得分:1)
Array.prototype.map()
和Map
可以结合使用arrays
有效地比较keys
。
请参阅下面的实例。
// Input.
const rooms = [{room_no: 1, bed_no: '1A'}, {room_no: 1, bed_no: '1B'}, {room_no: 2, bed_no: '2A'}, {room_no: 3, bed_no: '3A'}, {room_no: 3, bed_no: '3B'}, {room_no: 4,bed_no: '4A'}]
const patients = [{patient: {name: 'patient1', age: 22}, room: {room_no: 1,bed_no: '1A'}, status: 'occupied'}, {room: {room_no: 1, bed_no: '1B'}, status: 'available'}, {patient: {name:'patient2',age:32}, room: {room_no:2,bed_no: '2A'}, status:'occupied' }, {room: {room_no: 3, bed_no:'3A'}, status: 'cleaning'}]
// Room Status.
const roomStatus = (rooms, patients) => (m => rooms.map(r => m.get(`${r.room_no} ${r.bed_no}`) || {room: r, status: 'available'}))(new Map(patients.map(x => [`${x.room.room_no} ${x.room.bed_no}`, x])))
// Output.
const output = roomStatus(rooms, patients)
// Proof.
console.log(output)