How to iterate over a JavaScript object? How to iterate over a JavaScript object? javascript javascript

How to iterate over a JavaScript object?


For most objects, use for .. in :

for (let 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 (let 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

let keys = Object.keys(yourobject);

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

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

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

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


Here is another iteration solution for modern browsers:

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

Or without the filter function:

Object.keys(obj).forEach((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.


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 extrasObject.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