junaidh junaidh - 5 months ago 60
JSON Question

How to write if statement in JSON?

I don't know json , I have for loop statement.I need only single data , How can write if statement in JSON. Please help me,

function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td> " +
arr[i].offerPercentage +
"</td><td>" +
arr[i].offerName +
"</td></tr>";
}enter code here
out += "</table>";
document.getElementById("id01").innerHTML = out;
}

Answer

Edit: Now that it's clear what you want, to loop over just a single item, you change the amount of times to iterate - currently it will iterate over the whole array, to only iterate over one change arr.length to 1 (or however many items you want to display):

function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "<table>";    

    for(i = 0; i < 1; i++) {
        out += "<tr><td> " +
        arr[0].offerPercentage +
        "</td><td>" +
        arr[0].offerName +      
        "</td></tr>";
    }

    out += "</table>";
    document.getElementById("id01").innerHTML = out;
}

or you could simply reference the first result directly and bypass the loop which would make more sense:

function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "<table>";

    // Only append if `arr` has at least one result.
    if (typeof arr[0] !== 'undefined') {
        out += "<tr><td> " + 
        arr[0].offerPercentage +
        "</td><td>" +
        arr[0].offerName +      
        "</td></tr>";
    }

    out += "</table>";
    document.getElementById("id01").innerHTML = out;
}

Old Answer: Objects in Javascript don't have a .length property.

To loop over an object, use the for...in syntax:

for (var offer in arr) {
    // `offer.offerPercentage` and `offer.offerName` will be available here.
}

If what's being returned is actually an array, your issue isn't your syntax, it's the fact that you are using arr[0] in each loop rather than arr[i].