javascript tutorial - [Solved-5 Solutions] How to loop through or enumuerate a javascript object ? - javascript - java script - javascript array
Problem:
We have a JavaScript object like the following:
- Now we want to loop through all p elements (p1,p2,p3...) and get their keys and values. How can we do that?
- We can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible we want to avoid using eval.
Solution 1:
We can use the for-in loop as shown by others. However, we also want to make sure that the key we get is an actual property of an object, and doesn't come from the prototype:
Solution 2:
Under ECMAScript 5, we can combine Object.keys() and Array.prototype.forEach():
ES2016 adds for...of :
ES2017 adds Object.entries() which avoids having to look up each value in the original object:
Both Object.keys() and Object.entries() iterate properties in the same order as a for...inloop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
Solution 2:
We have to use the for-in loop But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain. Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:
Solution 3:
We can just iterate over it like:
Note that key will not take on the value of the property, it's just an index value.
Solution 4:
via prototype with forEach() which should skip the prototype chain properties:
Solution 5:
After looking through all the answers in here, hasOwnProperty isn't required for my own usage because my json object is clean; there's really no sense in adding any additional javascript processing. This is all I'm using: