简体   繁体   中英

Update one array of hash based on key value of other array of hash

I have following two array of hashes. I am trying to remove the record from doctor array hash whose doctor_patient_id doesnt not exist in doctor_patient_id array of patient_and_doctor array of hash.

doctor = [
  { :doctor_patient_id=>"abc",
    :doctor_id=>"d1"
  },
  { :doctor_patient_id=>"def",
    :doctor_id=>"d2"
  },
  { :doctor_patient_id=>"ghi",
    :doctor_id=>"d3"
  }
]

patient_and_doctor = [
  { :patient_id=>"11e8f37477ab7028a66b210b9699def9",
    :doctor_patient_id=>[ "def", "zkj", "cps" ]
  },
  { :patient_id=>"11e8f37481fabfe68630f5da2e22dceb",
    :doctor_patient_id=>[ "uio", "ghi", "jkk" ]
  }
]

expected output is:

doctor = [
      { :doctor_patient_id=>"def",
        :doctor_id=>”d2”
      },
      { :doctor_patient_id=>"ghi",
        :doctor_id=>”d3”
      }
    ]

I tried to do something like below but no luck,

patient_and_doctor.each do |dp|
  data = doctor.map {|d| d[:doctor_patient_id].include? 
   dp[:doctor_patient_id] }
end

How can i achieve this?

valid_ids = patient_and_doctor.flat_map { |h| h[:doctor_patient_id] }
# => ["def", "zkj", "cps", "uio", "ghi", "jkk"]

doctor.select { |h| valid_ids.include? h[:doctor_patient_id] }
# => [{:doctor_patient_id=>"def", :doctor_id=>"d2"},
#     {:doctor_patient_id=>"ghi", :doctor_id=>"d3"}]

use select! instead of select if you wish to mutate your doctor array instead of returning a new one.

以下可以获得必要的答案,

doctor.select { |x|  patient_and_doctor.map { |x| x[:doctor_patient_id] }.flatten.include?(x[:doctor_patient_id]) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM