Catch up to 3 foreach position

Asked

Viewed 336 times

0

I have a foreach which prints all categories of a JSON. How do I make him take only up to 3 position and stop the loop? The point is I want to create a menu ul with 3 categories and within it create another li with a sub-menu listing the rest of them. If there are 10 categories then it lists the top 3 in the top 3 li and then at 7 in this submenu inside the li next.

Follows the code:

var quantidadeElementos = retorno.data.length;

            var i = 0;
            while (i <= quantidadeElementos)
            {

              if (i == 3)
              {
                  retorno.data.forEach(function(item)
                 {
                   console.log(item.nome);

                 })

                break;
              }

              i++;
            }
  • loop in loop?

  • Wouldn’t it be better to just make a cup like this? var quantidadeElementos = retorno.data.length.slice(0, 3);?

  • or so $.each(retorno.data, function(i, j){ if( i < 3 ) console.log(j.nome); else break; })

  • Thank you worked perfectly. My mistake was not passing the parameters necessary for the function to work

1 answer

0


Your problem is within the second loop, can do it this way:

var quantidadeElementos = retorno.data.length;

var i = 0;
while (i <= quantidadeElementos) {
    if (i < 3) {
        console.log(retorno.data[i].nome);
        break;
    }

    i++;
}

Another problem was that if your comparison continued to be i == 3, he would run the loop 4 times, that’s because the variable i starts with the value 0. This comparison has been replaced by i < 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.