Skip to main content
Inspiring
October 6, 2015
Answered

use if/then inside .each loop

  • October 6, 2015
  • 1 reply
  • 684 views

hi all,

still a javascript jQuery newbie...

I want to add text inside the .each loop using an if/then statement - not sure how to do it...

basic.

$.each(data, function(key, value) {

            console. log ('item', key, value);

    output += "<li>" +

  value.id + " " + value.name + " " + value.date

  + "</li>";

  });

I tried this IF... : but doesn't work...

$.each(data, function(key, value) {

              console. log ('item', key, value);

      output += "<li>" +

  value.id + " " + value.name

  if (value.name == "Bob") {

  + " nice name "

  }

  " " + value.date

  + "</li>";

  });

Q: Any idea how to get it to work?

    This topic has been closed for replies.
    Correct answer sinious

    You're already performing the concatenation when you do this: output +=

    You know that it will keep what already exists in output and add to it (assuming this is assigned outside the loop). So you can just simply add more of the same thing.

    Inside the loop:

    output += '<li>' + value.id + ' ' + value.name;

    if (value.name == 'Bob') { output += ' nice name'; }

    output += ' ' + value.date + '</li>';

    Concatenate as much as you like. Unless you're dealing with crazy amounts of data, for a new person the performance impact of several concatenations is negligible.

    1 reply

    sinious
    siniousCorrect answer
    Legend
    October 7, 2015

    You're already performing the concatenation when you do this: output +=

    You know that it will keep what already exists in output and add to it (assuming this is assigned outside the loop). So you can just simply add more of the same thing.

    Inside the loop:

    output += '<li>' + value.id + ' ' + value.name;

    if (value.name == 'Bob') { output += ' nice name'; }

    output += ' ' + value.date + '</li>';

    Concatenate as much as you like. Unless you're dealing with crazy amounts of data, for a new person the performance impact of several concatenations is negligible.

    revdaveAuthor
    Inspiring
    October 10, 2015

    hi sinious,

    Thanks - that makes sense.