"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Traverse an Object (Tree) Recursively in JavaScript or jQuery?

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

Posted on 2025-03-23
Browse:761

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:

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
  }
}

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:

for (var key in foo) {
  if (!foo.hasOwnProperty(key)) continue;
  if (key == "child") {
    // Do something with child
  }
}

Recursive Looping

To loop recursively, create a recursive function:

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
    }
  }
}

This function can handle both objects and arrays, traversing their nested structure recursively.

Release Statement This article is reproduced on: 1729579817 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3