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

How to Flatten a Nested Object\'s Property List with Hierarchy?

Susan Sarandon
Release: 2024-10-20 14:30:02
Original
792 people have browsed it

How to Flatten a Nested Object's Property List with Hierarchy?

Recursive Looping Through an Object to Build a Property List

Problem:
Creating a flattened list of property keys from a complex object with multiple levels of nesting, while maintaining the hierarchy.

Underlying Data Structure:
The given object has a hierarchical structure with properties at different levels.

Desired Output:
A list of property keys that reflect the hierarchy.

Initial Approach:
A basic recursion function, iterate, is provided to loop through the object and print the property keys. However, it does not maintain the hierarchy.

Solution:
To account for the hierarchy, a stack variable is introduced to store the current path in the object. As the recursion function traverses the object, it appends the current property to the stack. When a primitive property is encountered, it is printed along with the concatenated stack, representing the full path to that property.

Revised Code:

<code class="js">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(stack + "." + property);
        $('#output').append($('<div>').text(stack + "." + property));
      }
    }
  }
}

iterate(object, "");</code>
Copy after login

Updated Solution:
The updated solution in the referenced answer provides a cleaner implementation using a combination of map and reduce functions to recursively traverse the object and build the flattened list of property keys.

<code class="js">Object.keys(object).map(key => createPath(object, key, "")).reduce((a, b) => a.concat(b))</code>
Copy after login

Function Explanation:

  • createPath: Recursively constructs the property path from the root object to the current property.
  • reduce: Combines the arrays of property paths from all properties into a single flattened array.

The above is the detailed content of How to Flatten a Nested Object\'s Property List with Hierarchy?. 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!