Home  >  Article  >  Web Front-end  >  How to Recursively Create Hierarchical Property Lists in JavaScript?

How to Recursively Create Hierarchical Property Lists in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 14:28:02519browse

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

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!

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