课程: JavaScript: Five Advanced Challenges and Concepts

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

Using a data map to turn flat arrays into trees

Using a data map to turn flat arrays into trees

- [Instructor] Presented with a flat array like this one there's an immediate question in need of an answer. What is the most efficient way of stepping through the data in this array? Now admittedly, this array only has four items so performance isn't really an issue. But imagine if it had a hundred items or a thousand items or 10,000 items and you get the idea. To turn this flat array into a nested one we have to open each item in the array then look at its parent property, then go back and open all the other items in the array to find if there is one that has an ID that matches the parent property. This is a lot of recursive looping and extremely inefficient when we have a lot of data. Fortunately, there's a better way of doing this. We can create a data map object from the original array where each array item is turned into a key value pair, where the key is the ID for the item and the value is the item itself. Looks…

内容