- Assumption: product_id is unique
For an array there is no other way but to loop through it all. You should consider changing your datamodel into a JSON then it will become much easier.
In your example
var products = [
0 [product_id, title, description]
1 [1234, apple, this is just apple]
2 [2345, pineapple, this is not just apple]
]
becomes
var products = {
product_id: [product_id, title, description],
1234: [1234, apple, this is just apple],
2345: [2345, pineapple, this is not just apple]
}
Now you can simply say
var select_1234 = products[1234];
to get the product of 1234.
If you must stick with the array and you need to find products multiple times, consider doing a transform at the beginning of your app to change it into json. As such you have indexed your data and now you can again call
products[1234]
EDIT
Alternatively, you can create json data to link to your array for example
var productsIndex = {
product_id: 0,
1234: 1,
2345: 2
}
This links to the position of the array so now you can call
var find = productsIndex[1234];
var select_1234 = products[find]; //This is the original array.
As an extra, consider using async transformations to transform the data so it does not freeze up any UI.
This can be done using a recursive setTimeout with 0 seconds
var products = {
product_id: [product_id, title, description],
1234: [1234, apple, this is just apple],
2345: [2345, pineapple, this is not just apple]
}
var productsIndex = {}
function recursiveTransform(val){
setTimeout(function(){
productsIndex[products[val].[0]] = val; //products[val].[0] is the product id of each array element
if (val != products.length -1) recursiveTransform(val+1);
}, 0)
}
recursiveTransform(0);
By doing this, you will not freeze up your ui or any other operation that might need to be run during the process
- I haven't tested the code but it should give you an idea
[{id: 1, title: 'Foo', description: 'baz'}, ...]