How to Loop Through a JavaScript Object
Topic: JavaScript / jQueryPrev|Next
Answer: Use the for...in
Loop
You can simply use the for...in
statement to loop through or iterates over all enumerable properties of an object in JavaScript. The for...in
loop is specifically built for iterating object properties.
Let's try out the following example to understand how it basically works:
Example
Try this code »// Sample object
var obj = {
make: "Ford",
model: "Mustang",
color: "red",
year: 2021
};
// Iterate through object properties
for(var key in obj) {
document.write("<p>" + key + " -> " + obj[key] + "</p>");
}
Related FAQ
Here are some more FAQ related to this topic: