Many people don’t realize the power and potential of the
Array.reduce (MDN) method. What makes it so powerful is its ability to take in an array containing any values and then return almost any type of data. Because of this flexibility, I want to highlight one technique you can use to traverse an array containing an infinite number of nested objects. You’ll learn how to accumulate all objects and return a single object you can use to reference any entry by ID.
Building out the Function
First, we’ll start with the data, an object with a structure that looks like this:
The objective here is to turn this array of nested objects into a flattened object so you can efficiently look up any entry by ID. Begin by creating the base function which accepts two arguments,
list and the
accumulator. Right off the bat, you might find this a little funny, passing around the reduce accumulator outside of the reduce method. Bear with me; this is where all the magic happens!
Now take the list argument and call reduces to return a value other than
Take notice of line 4, when we recursively call the
collect function, the resulting object is passed down and returned each time. Each iteration adds to the same object. Neat!
Next, you’ll set the object key to the current ID and assign it the value of
You might call this finished if the object didn’t contain nested objects. In order to collect all those values too, you will need to recursivly call
collect if the current object contains the
This is working great, but you can take this one step further and clean up the
children property. You may want to do this so you have less duplicate data.
Using Map Instead of an Object
Maybe you want to spice things up a bit and use some of the newer ES6 features like
Map. Swap out any references to the accumulator object and replace that value with
Map. Update the object assignments to use the
set method and that’s it!
There you have it, my thought process on how I would take a similar piece of data and transform it into something I can easily referenceable. Hopefully, there’s something here you can takeaway and apply to your own work. Happy coding!
Hey there, I'm Devin, the creator of this blog. Outside the digital world, my time is well spent with my wife and two children. Whenever I get the chance, I enjoy listening to music or audiobooks, reading business books, and playing mobile games.