Tip 41: Create Iterable Properties with Generators
In Tip 14, Iterate Over Key-Value Data with Map and the Spread Operator, you learned how simple it is to loop over maps thanks to iterables. And once you can iterate over a collection, you have access to the spread operator, array methods, and many other tools to transform your data. Iterables give your data more flexibility by allowing you to access each piece of data individually.
You also know that objects don’t have a built-in iterator. You can’t loop over an object directly—you need to convert part of it to an array first. That can be a major problem when you want the structure of an object but the flexibility of an iterable.
In this tip, you’ll learn a technique that can make complex data structures as easy to use as simple arrays. You’re going to use a new specialized function called a generator to return data one piece at time. In the process, you’ll see how you can convert a deeply nested object into a simple structure.
That’s changing. Developers and library authors are discovering how to use generators. One of the best use cases so far is to use generators to transform objects into iterables.
What is a generator? The Mozilla Developer Network explains that a generator is a function that doesn’t fully execute its body immediately when called.