Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};

Presently I need to loop through all p elements (p1, p2, p3...) And get their keys and qualities. How might I do that?
I can alter the JavaScript object if essential. My definitive objective is to loop through some key worth sets and if possible I need to try not to utilize eval.
by

2 Answers

MounikaDasa
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]);
}
}
sandhya6gczb
Use for-of on object.keys()

let object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};

for (let key of Object.keys(object)) {
console.log(key + " : " + object[key])
}

Login / Signup to Answer the Question.