[Solved-6 Solutions] Iterate through object properties - javascript tutorial



Problem:

How does iterate through an object properties ?

Solution 1:

Iterator method convert to a standard JS object into an iterable object.

 var o = {a:1,b:2,c:3},
    a = [];
o[Symbol.iterator] = function*(){
                       var ok = Object.keys(this);
                            i = 0;
                       while (i < ok.length) yield this[ok[i++]];
                     };
for (var value of o) console.log(value);
// or you can even do like
a = [...o];
console.log(a);

Solution 2:

Using jQuery.

$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

Solution 3:

To requires additional property as hasownproperty

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

Object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, they are properties of object.

Solution 4:

We can use Object.keys(obj) to get an Array of properties defined on the object itself.

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

It is more readable than a for-in loop. It is supports for firefox, chrome and internet explorer.

Solution 5:

Using ECMAScript.

Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));

Solution 6:

We can use Object.entries:

for (const [key, value] of Object.entries(obj)) { }

or

Object.entries(obj).forEach(([key, value]) => ...)

We want to iterate over the values, then use Object.values:

for (const value of Object.values(obj)) { }

or

Object.values(obj).forEach(value => ...)

Related Searches to Iterate through object properties - javascript tutorial