What are all the different ways to Iterate through an Object in JavaScript
We can iterate through an object in multiple ways in JavaScript. Before showing all the different ways and what we get from each method, let us suppose that, we have the following code
now the ‘john’ object have three properties (id, name, city) and one method (tellDetails) on it. Among them, we made ‘city’ as non enumerable. It has one property on its prototype (country) and one method (tellMoreDetails).
Before iterating through the array, lets do console.log(john) to check what we get.
Here is the output for console.log(john)
we can see that ‘john’ object is showing only ‘id’, ‘name’, ‘tellDetails’ and not ‘city’ as we made it non-enumerable.
Lets iterate through the Object now
1 . For – in
with the above result, we can see that we are getting ‘id’, ‘name’, ‘tellDetails’, ‘country’ and ‘tellMoreDetails’ with “for…in…” method.
For..in.. iteration gives all the enumerable properties and methods of an Object along with the properties and methods from its prototype in JavaScript.
We cannot access non-enumerable properties and methods of an object using for..in.. loop in JavaScript.
2. Object.keys()
Object.keys() methods returns an array of all Enumerable properties and methods of an object.
Object.keys() method does not return non-enumerable and prototype properties and methods.
3. Object.entries()
Object.entries() returns an array of all Enumerable properties and methods along with their values of an object.
Similar to Object.keys(), Object.entries() also returns an array. But each array item in turn will be an array containing name value pairs.
4. Object.values()
Object.values() returns an array of values of Enumerable properties and methods of an object.
With Object.keys() we get only keys, with Object.values() we get only values and with Object.entries() we get both keys and values. All of these properties and methods must be enumerable.
5. Object.getOwnPropertyNames()
Object.getOwnPropertyNames() returns an array of both Enumerable and Non-Enumerable properties and method names of an object.
Depending on our requirement, we can use one or the other or a combination of for..in and Object.getOwnPropertyNames to find out the list of properties and methods available on an Object and its prototype in JavaScript.
For..in is the only one that is giving the names of properties and methods of an object’s prototype object.
Object.getOwnPropertyNames is the only method that is giving the names of non-enumerable properties and methods of an object.
Leave A Comment