Whisou138
Whisou138

Reputation: 481

Hiding element from append if value doesn't exist

I have an ajax call that is getting a success result object and setting certain attributes from it into a list of <option> tags, and this works great but I have a bug I'm trying to account for.

I'm getting some results that don't have details and I successfully accounted for this by essentially using a ternary operator to say "if the element has no details, set the data-details attribute to undefined".

This works, but now I'd like to refactor this to say "If this has no details, do not append to option list"

Is there a way, within this loop, to account for the issue and simply hide this result from my options?

for (let i = 0; i < result.length; i++) {
  $("#returnedProducts").append($("<option/>",
        {
            "srindex": i,
            "data-details": result[i]._source.details ? JSON.stringify(result[i]._source.details[1]) : undefined,
            "value": result[i]._source.category,
            "html": result[i]._source.category,
        }
    ));
}

Upvotes: 1

Views: 47

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156554

Like this?

for (let i = 0; i < result.length; i++) {
  if(result[i]._source.details) {
    $("#returnedProducts").append($("<option/>",
        {
            "srindex": i,
            "data-details": JSON.stringify(result[i]._source.details[1]),
            "value": result[i]._source.category,
            "html": result[i]._source.category,
        }
    ));
  }
}

Upvotes: 1

Related Questions