Merge Two Arrays of Objects Using a Shared Value

Originally published on 28 February, 2021 by Jacob Stordahl

Lately I've been rebuilding a site for a gym that has a REST API available through the service they use to manage all aspects of the business. The API is generally friendly to use but I've come across this specific issue multiple times...

In my template I need an array to iterate over, however the returned array of objects from the API doesn't contain everything I need inside the iteration. This means I need to have a second array of objects that has the same shape as the API response. The children of this second array must also contain an id that matches a child in the array returned from the API.

To illustrate this a little more clearly, here's a specific example...

Imagine a route of api.myapi.com/employees which returns an array of object where each object represents an employee. Each object contains the employee's name, an employee id, their email address and their availability. However I want display a photo of the employee in my template. The API in question only provides employee photos through a separate endpoint, `api.myapi.com/employees/photos. Like the first, this endpoint returns an array of objects, each representing an employee which contains the employee id and the image source.

The issue then is this; how do I merge these two arrays, matching their children by id so I can iterate over a single array in my template? Here's a TypeScript example that does just that...

const mergeById = (a1: Array<object>, a2: Array<object>) =>
  a1.map(itm: object | null => ({
    ...a2.find(e: object | null => (e.id === itm.id)),
    ...itm
}))

Please note that to use this function, replace '.id' in line 3 with the property you're using to match children. You can then simply call this function, passing the two arrays as arguments...

const finalArray = mergeById(array1, array2)

... and you now have a single array containing the data from both API calls which can be iterated over in a template.

© 2021 Jacob Stordahl | built with Steel