javascript - Iterate through object properties

ID : 362

viewed : 46

Tags : javascriptloopsobjectjavascript

Top 5 Answer for javascript - Iterate through object properties

vote vote


Iterating over properties requires this additional hasOwnProperty check:

for (var prop in obj) {     if (, prop)) {         // do stuff     } } 

It's necessary because an 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, but are still properties of obj.

hasOwnProperty simply checks to see if this is a property specific to this class, and not one inherited from the base class.

It's also possible to call hasOwnProperty through the object itself:

if (obj.hasOwnProperty(prop)) {     // do stuff } 

But this will fail if the object has an unrelated field with the same name:

var obj = { foo: 42, hasOwnProperty: 'lol' }; obj.hasOwnProperty('foo');  // TypeError: hasOwnProperty is not a function 

That's why it's safer to call it through Object.prototype instead:

var obj = { foo: 42, hasOwnProperty: 'lol' };, 'foo');  // true 
vote vote


As of JavaScript 1.8.5 you can use Object.keys(obj) to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key)).

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

This is better (and more readable) than using a for-in loop.

Its supported on these browsers:

  • Firefox (Gecko): 4 (2.0)
  • Chrome: 5
  • Internet Explorer: 9

See the Mozilla Developer Network Object.keys()'s reference for futher information.

vote vote


Girls and guys we are in 2019 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:

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


It's the statement (MDN, ECMAScript spec).

You can read it as "FOR every property IN the obj object, assign each property to the PROPT variable in turn".

vote vote


In up-to-date implementations of ES, you can use Object.entries:

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


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

If you just want to iterate over the values, then use Object.values:

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


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

Top 3 video Explaining javascript - Iterate through object properties