How do I loop through or enumerate a JavaScript object? How do I loop through or enumerate a JavaScript object? javascript javascript

How do I loop through or enumerate a JavaScript object?


You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {    "p1": "value1",    "p2": "value2",    "p3": "value3"};for (var key in p) {    if (p.hasOwnProperty(key)) {        console.log(key + " -> " + p[key]);    }}