Back to: JavaScript Tutorial For Beginners and Professionals
Traversing and Enumerate JavaScript Object Properties
In this article, I am going to discuss Traversing and Enumerate JavaScript Object Properties with Examples. Please read our previous article where we discussed How to Delete/Remove a Property from a JavaScript Object with Examples. Get All properties of Object/ Traversing/Enumerate an object’s properties. Since JavaScript ECMAScript5 version, there are 5 different ways to list/traverse or fetch the properties of an object:
- for… in loops
- Object.keys(objectName)
- Object.values(objectName)
- Object.entries(objectName)
- Object.getOwnPropertyNames(objectName)
1. JavaScript for… in loops
The JavaScript for…in Loop statement iterates the properties of an object. To access all key-value pairs we can use a for-in loop. For… in loop is used with arrays and objects, to access their elements (arrays) and properties (objects) respectively.
- For arrays/strings, for-in iterates over arrays indexes (0…length-1)
- For any other object, for-in iterates over objects properties
In for… in looping, the variable value starts from zero and increases itself with one until it reaches the length of the array.
Syntax:
for (let key in objectName) { //statement or block to execute console.log(key) // to print only object property keys/names console.log(objectName[key]) // to print only object property values console.log(key + ":" + objectName[key]); //To print both key and values }
What we discussed above is given in the below example.
Example: JavaScript Objects, for… in loop example
<html> <head> <title>JavaScript Objects, for... in loop example</title> </head> <body> <script> //Object Literal with few defined properties let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) console.log("person Object literal type? : ", typeof person);// object //Looping object properties for (let key in person) { console.log("The person object property key is -->", key); // to print only object property keys/names console.log("The person object, each property value is -->", person[key]) // to print only object property values console.log("To print both key and values -->", key + ":" + person[key]); //To print both key and values } </script> </body> </html>
Output:
In the above code, we have iterated/enumerated all properties of a person object using for… in loop. Using for… in loop, we can access both keys and values. Above we have accessed and print the person object property names using console.log(key); statement. Also, we are printing person object each properties value with console.log(person[key]); statement later we have printed both the property key and value with console.log(key + “:” + person[key]); statements.
The better way to loop through an object is to first convert an object into an array. Then we can loop through that array as we do for the normal array. We can convert an object into an array with three methods:
- Object.keys(objectName)
- Object.values(objectName)
- Object.entries(objectName)
2. JavaScript Object.keys(objectName) method
This method was introduced in JavaScript ECMAScript5. The Object.keys() method takes the object as an argument of which properties keys are to be returned. It creates and returns an array that contains all the properties keys of the given object. Once the object has been converted into an array using the Object.keys() method, we can loop through this array in the same way we do for a normal array using for… of loop.
Step1: Convert the object to get either its key, value, or both.
Step2: Loop through using for… of loop.
The reason why we have used for… of loop instead of for… in loop is due to the below difference between them.
JavaScript for… in loop:
It returns the indexes of the individual properties of an object. It iterates over all the enumerable property keys of an object. Consider the below covidYears array example looping it through for… in loop and for… of loop to see the difference.
<html> <head> <title>JavaScript Objects, for... in loop example</title> </head> <body> <script> // Returning enumerable properties of a simple array var covidYears = ['2019', '2020', '2021']; for (let key in covidYears) { console.log(`The property keys of array covidYears: ${key}`) } </script> </body> </html>
Output: It iterates over the indexes of an array & returns the indexes (0,1,2,) same is appearing in the output.
JavaScript for… of loop:
It returns either the property, value, or both of an object. It iterates over the values of an iterable object. Examples of iterable objects are arrays, string, and NodeLists.
<html> <head> <title>JavaScript Objects, for... in loop example</title> </head> <body> <script> // Returning enumerable properties of a simple array var covidYears = ['2019', '2020', '2021']; for (let key of covidYears) { console.log(`The property keys of array covidYears: ${key}`) } </script> </body> </html>
Output: It iterates over the keys of an object hence it returns the keys that are 2019, 2020, and 2021.
Syntax: Object.keys(obj)
Parameter: Obj – it is an object name whose properties keys are to be returned.
Note: The Object.keys() method returns an array that contains all the properties keys of the given object.
In JavaScript enumerable property means that a property can be viewable if it is iterated/ enumerated using for… in loop or Object.keys() method.
- Object.keys() is used for returning enumerable property keys of a simple array.
- Object.keys() is used for returning enumerable property keys of an array-like object.
- Object.keys() is used for returning enumerable property keys of an array-like object with random numeric property key ordering.
What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.keys() method iterate property keys of simple array
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of simple array example1</title> </head> <body> <script> // Returning enumerable property keys of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The properties of array covidYears: ', Object.keys(covidYears)); //returns all properties of an array //looping through arrays created from Object.keys() method const cY = Object.keys(covidYears); for (let key of cY) { console.log(`The property keys of array covidYears: ${key}`) } </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.keys() method returns the enumerable property keys of this array. Hence it returns an array of property keys of this array i.e.: [“0”, “1”, “2” ] where 0,1, and 2 are the indexes as keys of the element 2019, 2020, and 2021 values respectively in the simple array. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.keys() method iterate property keys of array-like object
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of array-like object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property keys of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) console.log("person Object literal type? : ", typeof person);// object console.log('The key of person object property is: ', Object.keys(person)); //returns an array of all properties //Looping through arrays created from Object.keys() method //getting the keys/property const Pers = Object.keys(person); for (let key of Pers) { console.log("Looping through keys of arrays Pers created from Object.keys() method -->", key); // to print only object property keys/names } </script> </body> </html>
Output:
In this example, an array like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, pincode: 400001 }; and the Object.keys() method returns the enumerable property keys of this array. Hence it returns an array of property keys of this array like object i.e.: [“firstName”, “lastName”, “age”, “location”, “pincode”] where firstName, lastName, age, location and pincode are the property keys respectively in the array like object.
The Object.keys() is used for returning property keys of an array-like object with random numeric property key ordering. Array-like object with random property key ordering, when using numeric property keys, the property keys are returned in the numerical order of keys that is in the ascending order of object’s property keys. What we discussed above is given in the below example.
Example3: JavaScript Objects, Object.keys() method iterate property keys of an array-like object with random property key ordering
<html> <head> <title>JavaScript Objects, Object.keys() method iterate property keys of array-like object with random property key ordering example3</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property keys of an array like object with random property key ordering. var randomObj = { 70: 'one', 21: 'two', 35: 'three' }; //display data console.log("Random key object: ", randomObj) console.log("Random Key object length: ", Object.getOwnPropertyNames(randomObj).length) console.log("Random key Object literal type? : ", typeof randomObj);// object console.log('The keys of Random object property is: ', Object.keys(randomObj)); //returns an array of all property keys //[21, 35, 70] //Looping through arrays created from Object.keys() method //getting the property keys const Rand = Object.keys(randomObj); for (let key of Rand) { console.log("Looping through keys of arrays Rand created from Object.keys() method -->", key); // to print only object property keys } </script> </body> </html>
Output:
In this example, an array-like object “randomObj” has three property keys {70: ‘one’, 21: ‘two’, 35: ‘three’}; in random ordering and the Object.keys() method returns the enumerable property keys of this array in the ascending order of the object’s property keys. Hence it returns keys in ascending order that is [“21”, “35”, “70”].
3. JavaScript Object.values(objectName)
This method was introduced in JavaScript ECMAScript5. The Object.values() method takes the object as an argument of which property values are to be returned. It creates and returns an array that contains all the property values of the given object. Once the object has been converted into an array using the Object.values() method, we can loop through this array in the same way we do for a normal array using for… of loop.
Step1: Convert the object to get either its key, value, or both.
Step2: Loop through using for… of loop.
Syntax: Object.values(obj)
Parameter: Obj – it is an object name whose property values are to be returned.
Note: Object.values() method returns an array that contains all the property values of the given object.
In JavaScript enumerable property means that a property can be viewable if it is iterated/ enumerated using for… in loop or Object.values() method.
- Object.values() is used for returning enumerable property values of a simple array.
- Object.values() is used for returning enumerable property values of an array-like object.
- Object.values() is used for returning enumerable property values of an array-like object with random property key ordering.
What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.values() method iterate property values of simple array
<html> <head> <title>JavaScript Objects, Object.values() method iterate property values of simple array example1</title> </head> <body> <script> // Returning enumerable property values of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The property values of array covidYears: ', Object.values(covidYears)); //returns an array of all property values //looping through arrays created from Object.values() method const cY = Object.values(covidYears); for (let value of cY) { console.log(`The property values of array covidYears: ${value}`) } </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.values() method returns the enumerable property values of this array. Hence it returns an array of property value of this array i.e.: [‘2019’, ‘2020’, ‘2021’] where 2019, 2020, and 2021 are the element values respectively in the simple array. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.values() method iterate property values of array-like object
<html> <head> <title>JavaScript Objects, Object.values() method iterate property values of array-like object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property values of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) console.log("person Object literal type? : ", typeof person);// object console.log('The values of person object property is: ', Object.values(person)); //returns an array of all property values //["Elon", "Musk", 25, "India", 400001] //Looping through arrays created from Object.values() method //getting the property values const Pers = Object.values(person); for (let value of Pers) { console.log("Looping through values of arrays Pers created from Object.values() method -->", value); // to print only object property values } </script> </body> </html>
Output:
In this example, an array-like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, pincode: 400001 }; and the Object.values() method returns the enumerable property values of this array. Hence it returns an array of property values of this array like object i.e.: [“Elon”, “Musk”, 25, “India”, 400001] where Elon, Musk, 25, India and 400001 are the property values respectively in the array like object.
Object.values() is used for returning property values of an array-like object with random property key ordering. Array-like object with random property key ordering, when using numeric property keys, the property values are returned in the numerical order of keys that is in the ascending order of the object’s property keys. What we discussed above is given in the below example.
Example3: JavaScript Objects, Object.values() method iterate property values of array-like object with random property key ordering
<html> <head> <title>JavaScript Objects, Object.values() method iterate property values of array like object with random property key ordering example3</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property values of an array like object with random property key ordering. var randomObj = { 70: 'one', 21: 'two', 35: 'three' }; //display data console.log("Random key object: ", randomObj) console.log("Random Key object length: ", Object.getOwnPropertyNames(randomObj).length) console.log("Random key Object literal type? : ", typeof randomObj);// object console.log('The values of Random object property is: ', Object.values(randomObj)); //returns an array of all property values //['two', 'three', 'one'] //Looping through arrays created from Object.values() method //getting the property values const Rand = Object.values(randomObj); for (let value of Rand) { console.log("Looping through values of arrays Rand created from Object.values() method -->", value); // to print only object property values } </script> </body> </html>
Output:
In this example, an array-like object “randomObj” has three property values {70: ‘one’, 21: ‘two’, 35: ‘three’}; in random ordering and the Object.values() method returns the enumerable property values of this array in the ascending order of the indices(keys). Hence it returns sorted values as per the ascending order of property numeric keys that is [“two”, “three”, “one”].
4. JavaScript Object.entries(objectName)
This method was introduced in JavaScript ECMAScript5. The Object.entries() method takes the object as an argument of which property’s string-keyed pairs [key, value] is to be returned. It creates and returns an array of arrays. Each inner array has two items. The first item is the property key and the second item is the property value. In short, it returns both the keys and the values of the given object.
Once the object has been converted into an array using the Object.entries() method, we can loop through this array in the same way we do for a normal array using for… of loop.
Step1: Convert the object to get either its key, value, or both.
Step2: Loop through using for… of loop.
Syntax: Object.entries(obj)
Parameter: Obj – it is an object name whose property’s string-keyed pairs [key, value] is to be returned.
Object.entries() method returns an array of arrays. Each inner array has two items. The first item is the property key and the second item is the property value. In short, it returns both the keys and the values of the given object.
Note:
In JavaScript enumerable property means that a property can be viewable if it is iterated/ enumerated or listed using for… in loop or Object.entries() method.
- Object.entries() is used for returning/listing all the properties [key, value] pairs of a simple array.
- Object.entries() is used for returning enumerable property [key, value] pairs of an array like object.
- Object.entries() is used for returning enumerable property [key, value] pairs of an array like object with random numeric property key ordering.
What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.entries() method iterate property [key, value] pairs of simple arrays
<html> <head> <title>JavaScript Objects, Object.entries() method iterate property [key, value] pairs of simple arrays example1</title> </head> <body> <script> // Returning enumerable property [key, value] pairs of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The property [key, value] pairs of array covidYears: ', Object.entries(covidYears)); //returns an array of all property [key, value] pairs //looping through arrays created from Object.entries() method const cY = Object.entries(covidYears); for (let [key, value] of cY) { console.log(`The property [key, value] pairs of array covidYears: ${key} : ${value}`)//To print both key and values } </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.entries() method returns the enumerable property [key, value] pairs of this array. Hence it returns an array of array that is array of [key, value] pair i.e.: [ [“0”, “2019”], [“1”, “2020”], [“2”, “2021”] ] where 0,1, and 2 are the indexes as key of the element 2019, 2020 and 2021 values respectively in the simple array. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.entries() method iterate property [key, value] pairs of arrays like object
<html> <head> <title>JavaScript Objects, Object.entries() method iterate property [key, value] pairs of arrays like object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property [key, value] pairs of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) console.log("person Object literal type? : ", typeof person);// object console.log('The property [key, value] pairs of person object is: ', Object.entries(person)); //returns an array of all property [key, value] pairs //[ ["firstName", "Elon"], ["lastName", "Musk"], ["age", 25], ["location", "India"], ["pincode", 400001] ] //Looping through arrays created from Object.entries() method //getting the property [key, value] pairs const Pers = Object.entries(person); for (let [key, value] of Pers) { console.log(`Looping through property[key, value] pairs of arrays Pers created from Object.entries() method --> ${key} : ${value}`); //to print both keys and values } </script> </body> </html>
Output:
In this example, an array like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, pincode: 400001 }; and the Object.entries() method returns the enumerable property [key, value] pairs of this array. Hence it returns an array of array that is array of [key, value] pair of this array like object i.e.: [ [“firstName”, “Elon”], [“lastName”, “Musk”], [“age”, 25], [“location”, “India”], [“pincode”, 400001]] where firstName: Elon, lastName: Musk, age: 25, location: India and pincode: 400001 are the property [key, value] pairs respectively in the array like object.
The Object.entries() is used for returning property [key, value] pairs of an array-like object with random property key ordering.
Array-like object with random property key ordering, when using numeric property keys, the property [key, value] pairs are returned in the numerical order of keys that is in the ascending order of object’s property keys. What we discussed above is given in the below example.
Example3: JavaScript Objects, Object.entries() method iterate property [key, value] pairs of arrays like object with random property key ordering
<html> <head> <title>JavaScript Objects, Object.entries() method iterate property [key, value] pairs of arrays like object with random property key ordering example3</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property [key, value] pairs of an array like object with random property key ordering. var randomObj = { 70: 'one', 21: 'two', 35: 'three' }; //display data console.log("Random key object: ", randomObj) console.log("Random Key object length: ", Object.getOwnPropertyNames(randomObj).length) console.log("Random key Object literal type? : ", typeof randomObj);// object console.log('The property [key, value] pairs of Random objects are: ', Object.entries(randomObj)); //returns an array of all property [key, value] pairs //[[21: 'two'], [35: 'three'], [70: 'one']] //Looping through arrays created from Object.entries() method //getting the property [key, value] pairs const Rand = Object.entries(randomObj); for (let [key, value] of Rand) { console.log(`Looping through property [key, value] pairs of arrays Rand created from Object.entries() method --> ${key}: ${value}`); // to print both keys and values } console.log('\n\n'); //returns an array of first property [key, value] pairs console.log('The first property [key, value] pair of Random object are: ', Object.entries(randomObj)[0]); </script> </body> </html>
Output:
In this example, an array-like object “randomObj” has three property values {70: ‘one’, 21: ‘two’, 35: ‘three’}; in random ordering and the Object.entries() method returns the enumerable property [key, value] pairs of this array in the ascending order of the indices(keys). Hence it returns sorted an array of an array that is an array of property [key, value] pairs of this array-like object as per the ascending order of property numeric keys that is [[21: ‘two’], [35: ‘three’], [70: ‘one’]]
5. JavaScript Object.getOwnPropertyNames(objectName)
In JavaScript Object.getOwnPropertyNames() method is an in-built method that takes the object as an argument, which returns an array containing all the properties names present in the given or passed object. The properties of an object include both fields (objects) as well as functions.
Syntax: Object.getOwnPropertyNames(obj)
Parameter: Obj – it is an object name whose property’s names are to be returned.
Object.getOwnPropertyNames() method returns an array containing all the properties names present in the given or passed object. The properties of an object include both fields (objects) as well as functions.
Note:
In JavaScript enumerable property means that a property can be viewable if it is enumerated or listed using for… in loop or Object.getOwnPropertyNames() method.
- Object.getOwnPropertyNames() method is used for returning an array containing all the properties names of a simple array.
- Object.getOwnPropertyNames() method is used for returning an array containing all the properties names of an array-like object.
What we discussed above is given in the below example.
Example1: JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of simple array
<html> <head> <title>JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of the simple array example1</title> </head> <body> <script> // Returning enumerable property [key, value] pairs of a simple array var covidYears = ['2019', '2020', '2021']; console.log('The sorted property names of array covidYears: ', Object.getOwnPropertyNames(covidYears).sort()); //sort() is an array method to sort alphabetically //Logging property names and values using Array.forEach loop Object.getOwnPropertyNames(covidYears).forEach( function (val, index, array) { console.log(`Looping property names & values of an array covidYears created from Object.getOwnPropertyNames() method: ${val} : ${covidYears[val]}`); }); </script> </body> </html>
Output:
In this example, an array “covidYears” has three property values [‘2019’, ‘2020’, ‘2021’] and the Object.getOwnPropertyNames() method returns the enumerable property names of this array. Hence it returns an array of all property’s names present in the given simple array i.e.: [“0”, “1”, “2”, “length”] where 0,1, and 2 are the indexes as the key of the element 2019, 2020 and 2021 values respectively in the simple array and the length property gives the number of elements present in the array or the size of an array. Sort() method is an array method used to sort the array in an ascending order based on properties keys. What we discussed above is given in the below example.
Example2: JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of arrays like object
<html> <head> <title>: JavaScript Objects, Object.getOwnPropertyNames() method iterate property names of arrays like object example2</title> </head> <body> <script> //Object Literal with few defined properties // Returning enumerable property names of an array like object. let person = { firstName: "Elon", //setting the value of property of person object lastName: "Musk", age: 25, location: "India", pincode: 400001 }; //display data console.log("person object: ", person) console.log("person object length: ", Object.getOwnPropertyNames(person).length) console.log("person object sorted properties names: ", Object.getOwnPropertyNames(person).sort()) //sort() is an array method to sort alphabetically console.log("person Object literal type? : ", typeof person);// object //Logging property names and values using Array.forEach Object.getOwnPropertyNames(person).forEach( function (val, index, array) { console.log(`Looping property names & values of an array person created from Object.getOwnPropertyNames() method: ${val} : ${person[val]}`); }); </script> </body> </html>
Output:
In this example, an array-like object “person” has 5 property values {firstName: “Elon”, lastName: “Musk”, age: 25, location: “India”, pincode: 400001 }; and the Object.getOwnPropertyNames() method returns the enumerable property names of this array-like object. Hence it returns an array of all property’s names present in the given array-like object i.e.: [“age”, “firstName”, “lastName”, “location”, “pincode”] where age, firstName, lastName, location, and Pincode are the sorted property names in the array-like object. It is sorted as we have used the sort() method to sort an array in an ascending order based on properties keys and the length property gives the number of property keys present in the object or the size of an object.
In the next article, I am going to discuss How to Find the Length of a JavaScript Object with Examples. Here, in this article, I try to explain How to Traversing and Enumerate JavaScript Object Properties with Examples and I hope you enjoy this Traversing and Enumerate JavaScript Object Properties article.