Pick up the 3 position of the foreach

0

I have a foreach that prints all categories of a JSON . How do I get him to only get up to 3 position and stop loop ? The issue is that I want to create a ul with 3 categories in the menu and create another li with a sub-menu listing the rest of them. If it is 10 categories then it lists the first 3 in the first 3 li and then the 7 in this submenu within the li following.

Follow 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++;
            }
    
asked by anonymous 19.07.2017 / 21:48

1 answer

0

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

var quantidadeElementos = retorno.data.length;

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

    i++;
}

Another problem I had is that if your comparison continued to be i == 3 , it would run loop 4 times, this is because i starts with 0 . This comparison was replaced by i < 3 .

    
19.07.2017 / 22:04