0

Im using a each loop and pulling from a JSON database. Currently this loop randomizes the JSON and outputs a random item in the DIV. Im trying to figure out how I can add to this and have it pick a random item from a category instead of everything.

Below is my code:

function similarProduct() {
    $.each(json, function(i,item){
        similarProduct = json[Math.floor(Math.random()*json.length)];
        similarProduct += '<div>' + '<img src="' + similarProduct.imageURL + '">' + '<h3>' + similarProduct.itemName + '</h3>' + '</div>';
    });

    $('#productSimilar').append(similarProduct);            
}   

My JSON format looks like this:

[
  {
  "itemName":"Organic Tomatoes",
  "imageURL":"",
  "itemCategory":"Tomatoes"
  },
  {
  "itemName":"Olive Oils",
  "imageURL":"",
  "itemCategory":"Olive Oil"
  }
]
jean-max
  • 1,640
  • 1
  • 18
  • 33
Tom
  • 305
  • 1
  • 3
  • 15
  • Please explain exactly what you are trying to achieve, and why you are looping over the collection in the first place. Also, you seem to be treating your function like a local variable. – Chris Pickford Dec 13 '16 at 16:38
  • 1
    All you need to do is sort the JSON array before you build your output. See [Sorting Array of Custom Objects](http://stackoverflow.com/questions/10723798/sorting-array-of-custom-objects-in-javascript) for refrence. – bobjoe Dec 13 '16 at 16:39
  • @ChrisPickford This code is taken from a product page I am creating. Currently the page shows an item and at the bottom I have a similar recipe div. Since all the pages are created dynamically, I am trying to loop over everything and show a similar item from a category for each item. – Tom Dec 13 '16 at 16:40
  • @bobjoe can you please update my code to give an example? Im new to this stuff and would really really appreciate it. Thanks! – Tom Dec 13 '16 at 16:43
  • 1
    This kind of logic should be done server side. But running with what you have already, first of all ditch the loop, it's pointless. Presuming `json` is an array of products in the same category, just use your RNG to pick one out to display. – Chris Pickford Dec 13 '16 at 16:43
  • 1
    Please see @JackBauer's answer. He has given a good example. – bobjoe Dec 13 '16 at 16:45
  • It works perfectly thank you all for your help! – Tom Dec 13 '16 at 16:46
  • @Tom Invest the time to learn the language and don't rely on quick fixes from the internet. This approach is fundamentally flawed. – Chris Pickford Dec 13 '16 at 16:48
  • @ChrisPickford i am in the process of learning. I only go to this forum after I really try everything to get something to work for advice – Tom Dec 13 '16 at 16:50

1 Answers1

1

You need to create a temporary array categoryItems with items from the category first and then pick a random item from that array.

function similarProduct() {
    var categoryItems = [];
    $.each(json, function(i, item){
        if(item.itemCategory == 'Tomatoes') categoryItems.push(item);
    });

    $.each(json, function(i,item){
        similarProduct = categoryItems[Math.floor(Math.random()*categoryItems.length)];
        similarProduct += '<div>' + '<img src="' + similarProduct.imageURL + '">' + '<h3>' + similarProduct.itemName + '</h3>' + '</div>';
    });

    $('#productSimilar').append(similarProduct);            
}
MakG
  • 1,254
  • 9
  • 14
  • Jack this works exactly as I needed it to work. Thank you so much! Great example! – Tom Dec 13 '16 at 16:46
  • I don't see how this is any improvement over the original code example. You've hardcoded "Tomatoes", this will obviously need to be dynamic. Two loops of ALL product data just to pick one random product?! – Chris Pickford Dec 13 '16 at 16:52
  • @ChrisPickford it works. like i said im no expert. im am learning – Tom Dec 13 '16 at 17:01