'How do you limit for-in loops in Javasript?
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
}
Solution 1:[1]
Without counters:
Object.keys(object).slice(0,4).map((property) => {
// do something with property
})
Solution 2:[2]
You could use a counter. Something like this:
let counter = 0;
for(property in object)
{
if (counter >= 5){
break;
}
counter++;
}
Solution 3:[3]
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;
}
Solution 4:[4]
(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
}
Solution 5:[5]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Fikowski |
| Solution 2 | HSBogdan |
| Solution 3 | Dave |
| Solution 4 | Joomer |
| Solution 5 |
