Javascript Tutorial looping through all properties of object

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

This is a Javascript tutorial showing you how to loop through all the properties of an object.

Looping properties in Javascript Object

Consider for example, this Javascript object named “John” which has a string property, integer, property, array, and object…

To iterate through all the properties of an object, you can use the Object.entries method.  Running this code in Node via the terminal, we see that it console.log out all the properties.

From the output, we see that the Object.entries() method returns an array.  That means that you can destructure the array element to pull of the “key” and “value” of each property like this …

Looping properties in Javascript Class

In ES6, we have class.   We can use the same Object.entries method to loop through the properties of a class.  Consider this class …

We output the properties same as before …

Note that Object.entries does not pick out any functions in the Javascript object.  This is because Object.entries only returns enumerable properties.  Functions and methods are non-enumerable properties.

What if we have a class SmartPerson that extends Person such as …

When we loop through all the properties of SmartPerson, it produces all the properties including the one it has inherited from Person as you can see…

 

 


Related Posts

Tags

Share This