Nikita Kuhta Nikita Kuhta - 5 months ago 19
Javascript Question

Javascript iterate object

I have an object in JavaScript:

{
abc : '....',
bca : '...',
zzz : '...',
xxx : '...',
ccc : '...',
.....
}


I want to use a for-loop to get its properties. And I want to iterate it in parts (not all object properties at once).

With a simple array I can do it with a standard for-loop:

for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last


But how to do it with objects?

Answer

For most objects, use for .. in :

for (var key in yourobject) {
  console.log(key, yourobject[key]);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (var key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

var keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 var keys = [];
 for (var key in yourobject) {      
     if (yourobject.hasOwnProperty(key)) keys.push(key);
 }

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (var i=300; i<keys.length && i<600; i++) { 
   console.log(keys[i], yourobject[keys[i]]);
}