0

I just think it's weird that I haven't found any topic or question about this yet, on how to set a limit to a For...In loop.

I want to iterate throught the keys in a object of Objects , like below :

for(let month in responseObject['Monthly Time Series'])
             {
                 console.log(month);
             }

However I want to set a limit to this loop , like for example : the first 6 keys , or the first 12 keys of the object.

If I wanted to this with a for loop it would be easy , I would simply have to do this :

for (let i = 0 ; i < 12; i++)
      {
        console.log(responseObject['Monthly Time Series'][i];
      }

That is not possible thought , since this is an object. What would the alternative be ?

izzypt
  • 130
  • 8
  • 3
    Use a separate counter variable with the `for..in` loop. –  Apr 01 '21 at 15:01
  • 2
    If you need to limit it, then for in is not the right tool for the job. You can slice the Object.values array and loop over that – epascarello Apr 01 '21 at 15:01
  • 1
    Also "the first 6 keys" probably doesn't mean what you think. The keys are delivered to the loop in an order determined by fixed rules of the runtime that you can't control. If you want a subset of the keys, you should use `Object.keys()` to extract them, then sort or filter them according to your requirements. – Pointy Apr 01 '21 at 15:04
  • https://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop – WOUNDEDStevenJones Apr 01 '21 at 15:04

1 Answers1

1

Just stick a condition within the loop that will force exit the loop when you want to?

int x = 0;
let month in responseObject['Monthly Time Series'])
        {
          console.log(responseObject[month];
          x = x+1;
           if(x>6)
            {
             month = (whatever the maximum value of responseObject is)
            }
        }