I have a JavaScript object like the following:
var p = { "p1": "value1", "p2": "value2", "p3": "value3" };
How do I loop through all of p‘s elements (p1, p2, p3…) and get their keys and values?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the
for-inloop 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:
For-of with Object.keys() alternative:
Notice the use of
for-ofinstead offor-in, if not used it will return undefined on named properties, andObject.keys()ensures the use of only the object’s own properties without the whole prototype-chain propertiesUsing the new
Object.entries()method:Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.