👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.
javascript iterate over object
The best way to iterate through JavaScript object on modern browsers is:
Here is an example:
var myObject = { string: "example", integer: 12 };
Object.entries(myObject).forEach(function ([key, value]) {
console.log(key, value)
});
The expected console output is:
string example
integer 12
For older browsers (before ES6), the only way to loop through JS objects is to use a for ... in
loop:
When you loop through an object with the for (var property in object) {
// Skip loop if the property is from prototype
if (object.hasOwnProperty(property)) {
// Do awesome stuff here
}
}
for ... in
loop, you need to check if the property belongs to the object or to the prototype.