Charlie
Charlie

Reputation: 59

JSON jQuery if statement

I want to be able to append the title_coupon value from the deal.options object but only if it exists. If options doesn't exist I want to get the title.coupon from data.deal. The below code works but it's obviously returning title.coupon from both deal.options and data.deal. Can someone help me construct the if statement?

This is my current code:

$.each(data.deal, function (x, deal) {
    $('#container').after('<tr><td>' + this.title_coupon + '</td><td>' + this.id + '</td></tr>');
    $.each(deal.options, function (x, options) {
        $.each(options, function (x, deal) {
            $('#container').append('<tr><td>' + this.title_coupon + '</td><td>' + this.id + '</td></tr>');
        });
    });
});

Upvotes: 0

Views: 954

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 32831

How about:

$.each(data.deal, function (x, deal) {
    var found = false;
    $.each(deal.options, function (x, options) {
        $.each(options, function (x, deal) {
            $('#container').append('<tr><td>' + this.title_coupon + '</td><td>' + this.id + '</td></tr>');
            found = true;
        });
    });
    if (!found) {
        $('#container').after('<tr><td>' + this.title_coupon + '</td><td>' + this.id + '</td></tr>');
    }
});

Upvotes: 1

Related Questions