Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have a JavaScript object like the following:

var p = { "p1": "value1", "p2": "value2", "p3": "value3" };

Now I want to loop through all p elements (p1, p2, p3...) And get their keys and values. How can I do that?

I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key-value pairs and if possible I want to avoid using eval.

1 Answer

0 votes
by (106k points)

To loop through or enumerate a JavaScript object you can use the for-in loop.

Below is the code snippet you can refer to:-

var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; 

for (var key in p) { 

if (p.hasOwnProperty(key)) { 

console.log(key + " -> " + p[key]); 

   }

 }

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...