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