Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a plain JavaScript object with the objects as members

How can I loop through all members in a JavaScript object, including values that are objects?

For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?

var validation_messages = {     "key_1": {         "your_name": "jimmy",         "your_msg": "hello world"     },     "key_2": {         "your_name": "billy",         "your_msg": "foo equals bar"     } } 
like image 841
edt Avatar asked May 28 '09 16:05

edt


People also ask

Can you loop through objects 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 many ways can you iterate objects in JavaScript?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.

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.

Can we apply for..of loop on 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.


1 Answers

for (var key in validation_messages) {     // skip loop if the property is from prototype     if (!validation_messages.hasOwnProperty(key)) continue;      var obj = validation_messages[key];     for (var prop in obj) {         // skip loop if the property is from prototype         if (!obj.hasOwnProperty(prop)) continue;          // your code         alert(prop + " = " + obj[prop]);     } } 
like image 80
AgileJon Avatar answered Sep 17 '22 15:09

AgileJon