Home  >  Article  >  Web Front-end  >  How to Traverse an Object (Tree) Recursively in JavaScript or jQuery?

How to Traverse an Object (Tree) Recursively in JavaScript or jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-10-22 20:56:10376browse

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" &amp;&amp; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn