logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Traverse JSON object to find paths leading to leaf nodes

author
Written by
Abhishek Goyan

12/09/2024

JSON

Sign in to read full article

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. JSON objects are often used in web APIs to represent complex data structures. If you're working with JSON data, you may need to traverse it to find paths leading to leaf nodes. In this blog, we will learn how to achieve that with a practical example.

Understanding the Structure

Let’s start with a sample JSON object, which represents a simple tree structure. Here’s our example JSON:

{ "A": { "B": { "D": {}, "E": {} }, "C": { "F": {}, "G": { "H": {} } } } }

In this JSON structure:

  • "A" is the root node.
  • "B" and "C" are child nodes of "A".
  • "D", "E", "F", "G", and "H" are leaf nodes (nodes without children) in this hierarchy.

The Objective

Our aim is to print all possible paths from the root node to each leaf node. For instance, from our sample JSON above, the output should look like:

A -> B -> D
A -> B -> E
A -> C -> F
A -> C -> G -> H

The Approach

To achieve this, we will use a recursive approach. Here's the plan:

  1. Create a function that takes the current node and the path so far as arguments.
  2. If the current node is a leaf (it has no children), print the path.
  3. If it has children, iterate over each child node, appending it to the current path, and call the function recursively.

The JavaScript Code

Here’s how you can implement this logic in JavaScript:

const json = { "A": { "B": { "D": {}, "E": {} }, "C": { "F": {}, "G": { "H": {} } } } }; function printPaths(obj, path) { // Check if the current object has any children const isLeaf = Object.keys(obj).length === 0; if (isLeaf) { // If it's a leaf, print the current path console.log(path); return; } // If it's not a leaf, iterate through the children for (const key in obj) { // Create a new path with the current key printPaths(obj[key], path ? `${path} -> ${key}` : key); } } // Invoke the function with the JSON object and an empty path printPaths(json, '');

How It Works

  • We define our JSON object and a function printPaths.
  • The function checks if the current node (obj) has any children. If not, it means we’ve reached a leaf node, so we print the accumulated path.
  • This path is built as we navigate through the tree, concatenating child keys to the path string.
  • When we encounter a non-leaf node, the function recursively calls itself for each child node.

Running the Code

When you run the above code in a JavaScript environment (like a browser console or Node.js), it will print the following output:

A -> B -> D
A -> B -> E
A -> C -> F
A -> C -> G -> H

Conclusion

By exploring this example, we've learned how to traverse a JSON object and print all the possible paths to leaf nodes efficiently. This technique can be invaluable when working with complex datasets in web development, allowing developers to navigate and extract data systematically. Whether you're developing an API, process data from a remote source, or simply exploring a data structure, understanding how to traverse JSON will be an essential part of your toolkit.

Popular Tags

JSONJavaScriptweb development

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

Related Articles

  • Implementing Event Delegation for DOM Events

    14/09/2024 | VanillaJS

  • Understanding Promises and Async/Await in Vanilla JavaScript

    22/10/2024 | VanillaJS

  • Create a Custom Event Emitter in JavaScript

    14/09/2024 | VanillaJS

  • Understanding JavaScript Scope Chain

    22/10/2024 | VanillaJS

  • Traverse JSON object to find paths leading to leaf nodes

    12/09/2024 | VanillaJS

  • Exploring Micro tasks vs Macro tasks in JavaScript

    25/07/2024 | VanillaJS

  • Understanding the JavaScript Event Loop

    22/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design