Home > Net >  How do you limit for-in loops in Javasript?
How do you limit for-in loops in Javasript?

Time:02-17

How can I limit for-in to 5 loops even if there are more properties in the object?

for(property in object){
    //do this stuff for the first 5 properties
}

CodePudding user response:

Without counters:

Object.keys(object).slice(0,4).map((property) => { 
    // do something with property
})

CodePudding user response:

You could use a counter. Something like this:

let counter = 0;
for(property in object)
{
  if (counter >= 5){
    break;
  }
  counter  ;
}

CodePudding user response:

You can use a break;

Like this

let props = 0;
for(property in object){
  //do this stuff for the first 5 properties
  props  ;
  if (props > 4)
    break;
}

CodePudding user response:

(Sniped very badly, but..) You can add a counter that then breaks the loop. Here is some code that works:

let i = 0;
for (property in object) {
    if (i   == 5) {break;}
    //do this stuff for the first 5 properties
}

If you wish to not use a for-in loop, you can use to a regular for loop:

for (let i = 0; i < object.length && i < 5; i  ) {
    var property = object[i];
    //do this stuff for the first 5 properties
}

CodePudding user response:

If your object have a get method you can do

for (let index = 0; index <= 4; index  ) {
  object.get(index);
}

otherwise you can use a counter

let counter = 0;
for (property in object) {
  // use property
  if (  counter == 5) break;
}
  • Related