This is basically a programming style question in javascript.
Sometimes when I'm coding I find myself looping through a collection of data, like for example, a collection of users:
var users = [
{
id: 'USER-435',
name: 'James',
email: '[email protected]'
},{
id: 'USER-7897',
name: 'Mark',
email: '[email protected]'
},{
id: 'USER-2345',
name: 'Harry',
email: '[email protected]'
}
]
Important: This data comes from the server and it needs to be in order.
If I want to get the properties of a specific user by its ID, I will have to loop through the array to find it.
So what I have done is to loop through the array once and create properties in the array with the user's ID as its key. This way I can access each user using its ID without looping through the array. Because the = operator creates a reference to the object and not a copy, each property added to the array will be a reference.
The only problem I have found is that if the ID of the user is a number it will be part of the array. So, if we have a collection with 3 users, with one of their ID been 120, that will set the length of the array to 121. A quick could be add the property as 'id-120', but it doesn't feel very clean.
I can also create a separate object for the collection instead of creating new properties in the array, but that will create a new object I need to take care of.
I just wanted to ask what people think about this type of pattern and if you have a better way of doing it.