Home > Article > Web Front-end > How to Traverse an Object (Tree) Recursively in JavaScript or jQuery?
Looping through an Object (Tree) Recursively
In JavaScript or jQuery, traversing an object and its descendants can be achieved using the for...in loop:
<code class="javascript">for (var key in foo) { if (key == "child") { // Do something with child } if (key == "bar") { // Do something with bar } if (key == "grand") { // Do something with grand } }</code>
Note that the for...in loop iterates over all enumerable properties, including those inherited from the object's prototype. To avoid acting on inherited properties, use hasOwnProperty:
<code class="javascript">for (var key in foo) { if (!foo.hasOwnProperty(key)) continue; if (key == "child") { // Do something with child } }</code>
Recursive Looping
To loop recursively, create a recursive function:
<code class="javascript">function eachRecursive(obj) { for (var key in obj) { if (typeof obj[key] === "object" && obj[key] !== null) { eachRecursive(obj[key]); } else { // Do something with primitive value } } }</code>
This function can handle both objects and arrays, traversing their nested structure recursively.
The above is the detailed content of How to Traverse an Object (Tree) Recursively in JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!