Home >Web Front-end >JS Tutorial >How Do I Iterate Through Nested Objects in JavaScript?
Looping Through a JavaScript Plain Object's Object Members
When working with JavaScript objects, it's often necessary to iterate through their members. However, when the object contains sub-objects, looping through them requires a specialized approach.
Key-Value Pair-Based Looping
To loop through a plain JavaScript object, you can use:
for (var key in object) { // Loop through the object's key-value pairs }
Example:
var validation_messages = { "key_1": { "your_name": "jimmy", "your_message": "hello world" }, "key_2": { "your_name": "billy", "your_message": "foo equals bar" } }; for (var key in validation_messages) { // Output: "jimmy" and "billy" console.log(validation_messages[key].your_name); // Output: "hello world" and "foo equals bar" console.log(validation_messages[key].your_message); }
Nested Object Iteration
When dealing with nested objects, you can use a nested loop:
for (var key in object) { if (!object.hasOwnProperty(key)) continue; // Skip prototype properties var subObject = object[key]; for (var subKey in subObject) { // Loop through the sub-object's key-value pairs } }
Example:
for (var key in validation_messages) { // If property exists in this object if (!validation_messages.hasOwnProperty(key)) continue; var subObject = validation_messages[key]; for (var subKey in subObject) { // If property exists in this sub-object if (!subObject.hasOwnProperty(subKey)) continue; // Output: "jimmy" and "billy" console.log(validation_messages[key].your_name); // Output: "hello world" and "foo equals bar" console.log(validation_messages[key].your_message); } }
This approach ensures that you iterate through all key-value pairs, even for nested objects.
The above is the detailed content of How Do I Iterate Through Nested Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!