0

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>');
        });
    });
});
5
  • 3
    Where is if statement? Commented Apr 15, 2014 at 10:28
  • it's not there, that's what i'm looking for :) Commented Apr 15, 2014 at 10:29
  • can you provide the JSON and the expected HTML? Commented Apr 15, 2014 at 10:34
  • jquery is just a library of javascript, use simple if() statement and fetch conditional data Commented Apr 15, 2014 at 10:34
  • A few things. This is very hard to read. You declare x multiple times, each time hiding the outer instance. The same with deal. Commented Apr 15, 2014 at 10:34

1 Answer 1

1

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>');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.