navigating through a JSON object containing various nested elements using JavaScript

My goal is to iterate through a Json object structured like this

    [
      {
        "yang_type": "container",
        "name": "c1",
        "value": "",
        "children": [
          {
            "yang_type": "",
            "name": "type",
            "value": "Uint32",
            "children": []
          },
          {
            "yang_type": "list",
            "name": "DNS",
            "value": "",
            "children": [
              {
                "name": "type",
                "value": "String",
                "children": [],
                "yang_type": ""
              },
              {
                "yang_type": "leaf",
                "name": "ip-address",
                "value": "",
                "children": [
                  {
                    "name": "type",
                    "value": "string",
                    "children": [],
                    "yang_type": ""
                  }
                ]
              },
              {
                "yang_type": "leaf",
                "name": "Domain",
                "value": "",
                "children": [
                  {
                    "name": "type",
                    "value": "string",
                    "children": [],
                    "yang_type": ""
                  }
                ]
              }
            ]
          }
        ]
      }
    ]

I've implemented the following logic, but it fails to iterate through all the children elements.

while(m.children.length >= 1) {
    if(m.yang_type!='' && m.name!=''){
       {$log.error("parent:",m.yang_type,m.name);}
    }
    if(m.name!='' && m.value!=''){
       {$log.error("child:",m.name,m.value);}
    }
    m = m.children[m.children.length - 1];   
}

The existing code seems to be missing the iteration over certain child nodes. What am I doing incorrectly?

Answer №1

Attempting to iterate over the array using a loop proved unsuccessful.

A callback can be utilized for iteration, with consideration given to implementing recursion for handling children elements.

function loop(level) {
    return function (a) {
        var i = level, s = '';
        while (i--) {
            s += '  ';
        }
        if (level) {
            s += '*';
        }
        a.yang_type ? 
            console.log(s + a.yang_type + ' ' + a.name) :
            console.log(s + a.name + ' ' + a.value);
        Array.isArray(a.children) && a.children.forEach(loop(level + 1));
    }
}

var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", "children": [], "yang_type....

Edit made on indented output.

function loop(a) {
    console.log(a.name);                                   // process you data
    Array.isArray(a.children) && a.children.forEach(loop); // check and iterate children
}

var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", ....

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect to a point on the leaflet map using an external <a> tag reference

I have a leaflet map and I am trying to create a link that, when clicked, will activate a specific marker on the map. Essentially, I want the linked marker to simulate being clicked when the link is clicked. Here is an example of the link: <a href="#" ...

Attempting to save API information into a database using PHP?

Currently, I am gathering deals from Groupon's API. While I have managed to display the data in HTML, I am having trouble transferring it to a database using PHP. I believe that storing this information in a database will provide me with more control ...

Updating the JSON property name in subclasses with the Jackson library

Currently in the process of developing a new REST API using Spring, I have created a BaseResponse class which serves as the foundation for all responses. Within this class, there is an attribute called String requestUuid;. In certain scenarios, this requ ...

Durandal attempts to retrieve a view located within the viewmodel directory

Having an issue with durandal's compose binding as it is looking for views under app/viewmodels instead of app/views The ViewModel code: define(["fields/fieldClosures"], function (fields) { var ctor = function(opt) { this.value = opt.valu ...

How to use Laravel to show a graph sourced from a separate database connection

Is it possible to create a pie or doughnut chart in Laravel using data from a separate database connection ('mysql2' in the .env file)? I have successfully generated charts from the main database, but this time I didn't migrate the second da ...

What is the best practice for AngularJs service methods: accepting an object or multiple parameters?

When creating Angular JS service methods, what is the recommended approach: accepting multiple parameters or utilizing an object? var getMessages = function (appid, userId, limit) { var data = { "appid": appid, "userId": userId, ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

Unable to create follow/unfollow feature with jquery ajax

Issue: While the database part for following and unfollowing actions is functioning correctly, there seems to be a problem with the jQuery and Ajax section. The follow button changes to unfollow (with some CSS styling) only after refreshing the page, rathe ...

Using Angular 6 to load external HTML files with CSS inside a router-outlet

I'm currently working on creating a json-based dynamic template using Angular 6. There are certain scenarios where I need to fetch external html content (which could be stored in a database) along with its corresponding css (also stored separately in ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Utilize GSON library to translate JSON into a MAP object

Is there a better way to convert JSON response to a Map using GSON library? I attempted the following code but I am only able to retrieve the ArrayList value. Map<String, Object> map = gson.fromJson(response, HashMap.class); ArrayList responseOption ...

Properly segmenting sections into components in Angular

My project has a specific folder structure as shown below: https://i.sstatic.net/7oihC.png In my list-page, I perform operations such as create, update, and delete using modal dialogs. I am considering creating 4 pages for each of these CRUD operations a ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Searching for root words in elasticsearch

After successfully implementing stemming for elasticsearch, I noticed that my searches for "code" also bring up results for "codes" and "coding," which is great. However, I encountered a problem when using the "must_not" field in my queries. Including "co ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Tips for keeping your button fixed in place

I am encountering an issue where my button moves below the select dropdown list when I try to make a selection. Is there a way to keep the button in place even when the dropdown list from the select box is visible? For reference, here is the current outp ...

What is the process for making a referenced variable null?

My scenario is as follows: When a user clicks on a button in Phaser.io, I create a new Phaser.sprite and store it in a local variable called newSquare. This new sprite is then added to an array called Squares. At a later point, I call a function to destr ...

Streamline List - Identical Field

Encountering an issue with XStream, specifically when dealing with a java class named simplePerson. The class structure is as follows: public class SimplePerson { @XStreamAlias("name") private String name; private List<String> cars; Attempting to ...

Exploring the process of including cube quantities in three.js code

In my current project, I am facing a challenge of incorporating multiple spheres into the scene. Initially, there were only three cubes present, but now I need to include around 10 spheres that are evenly spaced from each other and are rotating at varying ...