Search code examples
javascriptarraysobject

Javascript: Object Array merging on criteria


I have the following 3 array of objects

let recipients = [{"blackList":"0","clawfulBasis":"3","cmOneID":"0","id":"13251316","jurisdiction":"SCPB - LON","name":"David G","relationshipManager":"Adam Cavalier","subscription":"","_schema":"nms:recipient"},{"blackList":"0","clawfulBasis":"3","cmOneID":"666666","id":"13251376","jurisdiction":"Guernsey","name":"David Llanos Changed Garcia","relationshipManager":"Adam Cavalier","_schema":"nms:recipient"}];

let services = [{"id":"3218143","name":"SVC27","label":"UK > Financial Advisers > Services"},{"id":"3721","name":"newsletter","label":"Newsletter"},{"id":"15656200","name":"SVC35","label":"Sustainability"}]

let serviceSubscriptions =  [{"recipientId":"13251316","serviceId":"3218143"},{"recipientId":"13251376","serviceId":"15656200"},{"recipientId":"13251376","serviceId":"15656200"},{"recipientId":"13251376","serviceId":"3721"}]

serviceSubscriptions contains recipients that are subscripbed to services, what I would like to do is enrich the recipient objects to contain their subscriptions something like the below, the id attribute of recipient object is the recipientId attribute of the serviceSubscriptions and can be used to match.

{"blackList":"0","clawfulBasis":"3","cmOneID":"666666","id":"13251376","jurisdiction":"Guernsey","name":"David Llanos Changed Garcia","relationshipManager":"Adam Cavalier","subscriptions":"[3218143,15656200,3721]","_schema":"nms:recipient"}


Solution

  • In pseudocode, you want to loop through each serviceSubscription. For each serviceSubscription, find the recipient record by recipientId and append the serviceId to the recipient's subscriptions value.

    This is quite slow, but you can optimize it based on your needs (how large is serviceSubscription, how large is recipients, etc.). For example, you could modify this by building a hash from serviceSubscriptions where the key is the recipientId and the value is a list of each recipients subscriptions. Then you could simply map through the recipients list, and check if there is a subscription list that you need to append once.