I have a Product javascript array, which contains all the products information. Created a function which iterate on this array and find the product by matching id.
var products = JSON.parse('[{"Product":{"id":"1","name":"My Product","description":"This is my new product","price":"10.00","currency":"$","stock":"0","image":"/image1.png"}},{"Product":{"id":"5","name":"Dummy Product 2","description":"Some dummy text goes here.","price":"10.00","currency":"$","stock":"100","image":"image2.jpg"}}]');
$(document).ready(function(){
console.log(products);
alert(findProduct(5)); //it will returns false everytime, evan it has matching product
});
function findProduct(product_id){
$.each(products, function(k, v){
if(v.Product.id == product_id){
console.log(v);
return products[k]; //or return 'v'
}
});
return false;
}
Check this Demo
Function returns false each time, even though it found the matching product id, don't know why? If I store the matching array key in a variable and after iteration, return the value of that key it returns proper object. But that's not proper way, cause I want to stop iteration and return the value if object found.