Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-22 20:56:10
Original
316 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!