Tom Tom - 20 days ago 7
jQuery Question

Need assitance with IF statement and JSON

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"
],
}
]




Answer

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>

Comments