Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" }; 

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.

like image 304
Tanmoy Avatar asked Mar 26 '09 06:03

Tanmoy


People also ask

How do you loop through or enumerate JavaScript object?

Loop and Enumerate Object Properties with Object.data. forEach(([key, value], index) => { console. log(`Index: ${index} | I scored ${value} in my ${key} subject!`) })

Can you loop through an object JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

How do I iterate over an object key?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.


2 Answers

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]);      }  }

For-of with Object.keys() alternative:

var p = {      0: "value1",      "b": "value2",      key: "value3"  };    for (var key of Object.keys(p)) {      console.log(key + " -> " + p[key])  }

Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = {     "p1": "value1",     "p2": "value2",     "p3": "value3" };  for (let [key, value] of Object.entries(p)) {   console.log(`${key}: ${value}`); } 
like image 154
levik Avatar answered Oct 03 '22 10:10

levik


Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };  Object.keys(obj).forEach(function(key) {     console.log(key, obj[key]); }); 

ECMAScript 6 adds for...of:

for (const key of Object.keys(obj)) {     console.log(key, obj[key]); } 

ECMAScript 8 adds Object.entries() which avoids having to look up each value in the original object:

Object.entries(obj).forEach(     ([key, value]) => console.log(key, value) ); 

You can combine for...of, destructuring, and Object.entries:

for (const [key, value] of Object.entries(obj)) {     console.log(key, value); } 

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

like image 39
Axel Rauschmayer Avatar answered Oct 03 '22 10:10

Axel Rauschmayer