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

How to Recursively Create Hierarchical Property Lists in JavaScript?

Barbara Streisand
Release: 2024-10-20 14:28:02
Original
516 people have browsed it

How to Recursively Create Hierarchical Property Lists in JavaScript?

Building Hierarchical Property Lists with Recursion

Looping through complex nested objects to construct hierarchical property lists is a common task in JavaScript. Given an object with a potentially complex structure, the goal is to generate a list of property keys that reflects the object's structure.

To address this, we can utilize a recursive function that traverses the object. Here's an improved version of the provided function:

function iterate(obj, stack) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (typeof obj[property] == "object") {
                iterate(obj[property], stack + '.' + property);
            } else {
                console.log(property + "   " + obj[property]);
                $('#output').append($("<div>").text(stack + '.' + property));
            }
        }
    }
}
Copy after login

In this function, we maintain a string called 'stack' that represents the current path within the object. When we encounter a sub-object, we append its property to the stack and continue the recursion. For primitive properties, we log and append their paths to a div for visualization.

By invoking the 'iterate' function with the original object and an empty initial stack, we can recursively build the desired hierarchical list of property keys.

The above is the detailed content of How to Recursively Create Hierarchical Property Lists in JavaScript?. 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!