A simple function to retrieve an item from the array might look like this.
One of many reasons that databases like SQL are generally efficient at retrieving data is indexing. This is a very broad topic, that is outside the scope of this post. However the basic principle is that the database ‘knows’ where certain values in the database are, so it doesn’t have to search for them. A good example of database indexing is a phone book. The records in the book are ordered by surname. If you want to find someone with the surname ‘Jones’, you can quickly skip all of the irrelevant records and just scan through J. In a SQL database this is called a clustered index, and determines the actual order of data storage, so only one column name can be used for a clustered index.
And the function to retrieve an item
Now if you’re searching for broccoli, and you know it’s a vegetable, then your function only needs to iterate through half as much data to find your object. So, what if you don’t know the type? Your new indexed object can still be iterated through in the long-hand fashion. A slight modification to the function can check to see if ‘context’ is defined, and if not, just use an extra loop.
If you need to deal with a large number of very large objects, it can be worth setting up an extra array, just for indexing. This is equivalent to a non-clustered index in SQL. It is very much like the index at the back of a book, which you can use to find the page number of a particular record. So when building your large array, also create an object that just holds information about the larger one.
This might seem pointless at first glance, but it provides a lightweight object that can be queried to find the location of an object based on your chosen property name. So, this time, if you want to retrieve the broccoli object, all you need to do is this.
This saves iterating through what could be thousands of large objects, inspecting their values. This indexing method will only work with a property that you know holds unique values. Even if you’re retrieving your large array from somewhere else, i.e. some JSON from another server, you could perform an initial loop through it to index your values, giving you fast access for later on.