1

I am trying to figure out how I can use an if statement to filter my JSON results on a page. Each recipe has its own category and I am trying to be able to filter the information based on type category type and other paramaters. I only included some code for people to get the idea but when I run this I get nothing. Here is my code:

$.each(json, function(i, item) {
 if (item.recipeCategories == "fall") { 
       //show correct items in div
    }
});
var json = 
    
[
   {   
    "recipeName":"Crispy Zucchini Fritte with Lemon Aioli",
    "recipeCategories":[
             "appetizers",
       "spring"
       ],
 },
    {   
    "recipeName":"Hummus Tahini",
    "recipeCategories":[
             "desserts",
       "fall"
       ],
 }
]
Tom
  • 305
  • 1
  • 3
  • 15
  • That's not JSON. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Nov 14 '16 at 17:52
  • its in a JSON file – Tom Nov 14 '16 at 17:54
  • 1
    Fair enough. :-) But by the time you're doing what you describe above, it's not JSON anymore. It's been parsed into an array of objects. – T.J. Crowder Nov 14 '16 at 17:55

2 Answers2

1

This line:

if (item.recipeCategories == "fall") {

checks to see if item.recipeCategories is == to "fall", but the recipeCategories in your array of objects is, itself, an array. You may want indexOf (or in really modern JavaScript, includes):

if (item.recipeCategories.indexOf("fall") !== -1) {

as of ES2016 (and can be shimmed):

if (item.recipeCategories.includes("fall")) {

Example:

var json = [
    {
        "recipeName": "Crispy Zucchini Fritte with Lemon Aioli",
        "recipeCategories": ["appetizers", "spring"],
 },
    {
        "recipeName": "Hummus Tahini",
        "recipeCategories": ["desserts", "fall"],
    }
];
$.each(json, function(i, item) {
    if (item.recipeCategories.indexOf("fall") != -1) {
        $("<div>").text(item.recipeName).appendTo(document.body);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Since recipeCategories is an array then you can use indexOf.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

See this bin for usage: https://jsbin.com/xilarewafe/edit?html,js,output