How to iterate over a JavaScript object?

How to iterate over a JavaScript 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?

Solutions/Answers:

Solution 1:

For most objects, use for .. in :

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

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

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

You don’t need to check hasOwnProperty when iterating on keys if you’re using a simple object (for example one you made yourself with {}).

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]]);
}

Solution 2:

Here is another iteration solution for modern browsers:

Object.keys(obj).filter(function(k, i) {
    return i >= 100 && i < 300;
}).forEach(function(k) {
    console.log(obj[k]);
});

Or even shorter:

Object.keys(obj).forEach(function(k, i) {
    if (i >= 100 && i < 300) {
        console.log(obj[k]);
    }
});

However you must consider that properties in JavaScript object are not sorted, i.e. have no order.

Solution 3:

With the new ES6/ES2015 features, you don’t have to use an object anymore to iterate over a hash. You can use a Map. Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.

Iterate over a map:

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

for (var key of myMap.keys()) {
  console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"

for (var value of myMap.values()) {
  console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

or use forEach:

myMap.forEach(function(value, key) {
  console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

Solution 4:

Using Object.entries you do something like this.

 // array like object with random key ordering
 const anObj = { 100: 'a', 2: 'b', 7: 'c' };
 console.log(Object.entries(anObj)); // [ ['2', 'b'],['7', 'c'],['100', 'a'] ]

The Object.entries() method returns an array of a given object’s own enumerable property [key, value]

So you can iterate over the Object and have key and value for each of the object and get something like this.

const anObj = { 100: 'a', 2: 'b', 7: 'c' };
Object.entries(anObj).map(obj => {
   const key   = obj[0];
   const value = obj[1];

   // do whatever you want with those values.
});

or like this

// Or, using array extras
Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});

For a reference have a look at the MDN docs for Object Entries

Solution 5:

The only reliable way to do this would be to save your object data to 2 arrays, one of keys, and one for the data:

var keys = [];
var data = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        keys.push(key);
        data.push(obj[key]); // Not necessary, but cleaner, in my opinion. See the example below.
    }
}

You can then iterate over the arrays like you normally would:

for(var i = 0; i < 100; i++){
    console.log(keys[i], data[i]);
    //or
    console.log(keys[i], obj[keys[i]]); // harder to read, I think.
}
for(var i = 100; i < 300; i++){
    console.log(keys[i], data[i]);
}

I am not using Object.keys(obj), because that’s IE 9+.

Solution 6:

If you want the key and value when iterating, you can use a for…of loop with Object.entries.

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2