Tom Tom - 1 month ago 10
JSON Question

Want to use IF statement with JSON

I have very simple code taking items from a JSON file and displaying them in a DIV. However, currently I am accessing each item based on its order in the array. I want to add an IF statement in addition to each item incase the order gets changed in the JSON file. Each item has its own id as well. For example,

data[0].itemName
could end up becoming
data[1].itemName
if the JSON file is altered.

(function() {

'use strict';

var url = 'path to json';

$.getJSON(url, function(data) {

$('#recipeIngredients').html(

"<ul>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '2 cups ' + (data._id == "1" ? data.itemName : " ") + "</li>" +
"<li>" + data.itemName + "</li>" +
"</ul>");

});


})();

JSON is as follows:

var data = [ { "itemName" : "exampleItem1", "_id" : "1" }, { "itemName" : "exampleItem2", "_id" : "2" } ]

Answer

Test this example

var data = [{
  "id": "1",
  "itemName": "exampleItem1"
}, {
  "id": "2",
  "itemName": "exampleItem2"
}];
var ul = "<ul>";
for (var i = 0; i < data.length; i++) {
  ul += "<li>" + '1/2 tsp salt' + "</li>" +
    "<li>" + '2 cups ' +
    (data[i].id == "2" ? data[i].itemName : " ") +
    "</li>" +
    "<li>" + data[i].itemName + "</li>";

}
ul += "</ul>";
document.body.innerHTML = ul;

var data = [{
  "id": "1",
  "itemName": "exampleItem1"
}, {
  "id": "2",
  "itemName": "exampleItem2"
}];
var ul = "<ul>";
for (var i = 0; i < data.length; i++) {
  ul += "<li>" + '1/2 tsp salt' + "</li>" +
    "<li>" + '2 cups ';
//if statement should like this
if(data[i].id == "2") ul += data[i].itemName;
//add else if you want
else ul += "_ _ _";

  ul += "</li>" +
    "<li>" + data[i].itemName + "</li>";

}
ul += "</ul>";
document.body.innerHTML = ul;