Parsing JSON dynamically using JavaScript

Below is a JSON object that needs to be parsed to extract values only from the last children available in the list for each object:

        {
         "projectInfo": {
        "cabinetInfo": [
          {
            "nodeName": "EAST",
            "boxName": "EAST-Box",
            "children": [
              {
                "nodeName": "Street-3",
                "smsName": "smsname",
                "boxserilaNumber": 4004342423
              },
              {
                "nodeName": "Street-2",
                "smsName": "smsname",
                "boxserilaNumber": 4004342423
              },
              {
                "nodeName": "Street-1",
                "smsName": "smsname",
                "boxserilaNumber": 4004342423
              }
            ]
          },
          {
            "nodeName": "NORTH",
            "boxName": "NORTH-Box",
            "children": [
              {
                "nodeName": "ZONE1",
                "boxName": "ZONE1-Box",
                "children": [
                  {
                    "nodeName": "AREA",
                    "boxName": "AREA-Box",
                    "children": [
                      {
                        "nodeName": "Street-3",
                        "smsName": "smsname",
                        "boxserilaNumber": 4004342423
                      },
                      {
                        "nodeName": "Street-2",
                        "smsName": "smsname",
                        "boxserilaNumber": 4004342423
                      },
                      {
                        "nodeName": "Street-1",
                        "smsName": "smsname",
                        "boxserilaNumber": 4004342423
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            "nodeName": "SOUTH",
            "boxName": "SOUTH-Box",
            "children": [
              {
                "nodeName": "ZONE1",
                "boxName": "ZONE1-Box",
                "children": [
                  {
                    "nodeName": "SOCIETY",
                    "boxName": "SOCIETY-Box",
                    "children": [
                      {
                        "nodeName": "AREA",
                        "boxName": "AREA-Box",
                        "children": [
                          {
                            "nodeName": "Street-4",
                            "smsName": "smsname",
                            "boxserilaNumber": 4004342423
                          },
                          {
                            "nodeName": "Street-3",
                            "smsName": "smsname",
                            "boxserilaNumber": 4004342423
                          },
                          {
                            "nodeName": "Street-2",
                            "smsName": "smsname",
                            "boxserilaNumber": 4004342423
                          },
                          {
                            "nodeName": "Street-1",
                            "smsName": "smsname",
                            "boxserilaNumber": 4004342423
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
        }
        }

I attempted to code the function to extract the values but it is only retrieving 3 box serial numbers instead of 9. As a newcomer to JavaScript, I am struggling to identify the mistake in my code. I believe the issue lies in the renderCabinetInfoList method where I am recursively calling to reach the bottom of the list with children.

function renderCabinetInfo(nodeTree)
{
    var cabinetLists = nodeTree.projectInfo.cabinetInfo;
    for(var j=0;j<cabinetLists.length;j++)
    {
        var cabinetList = cabinetLists[j].children;
        var cabinetInfoTags = renderCabinetInfoList(cabinetList);
        var cTable=document.getElementById('cabinetInfoTable');
        for(var i=0;i<cabinetInfoTags.length;i++)
        {
            console.log(cabinetInfoTags[i].boxserilaNumber);
        }
    }  
};
function renderCabinetInfoList(cabinetList)
{
    for(var i=0;i<cabinetList.length;i++)
    {
        var cabi = cabinetList[i];
        if(haveChildren(cabi)) {
            renderCabinetInfoList(cabi.children);
        }
        else
        {               
            break;
        }
    }
    
    return cabinetList=cabinetList;
}
function haveChildren(cabi)
{
    if (null != cabi.children && cabi.children.length>0) {
            return true;
        }
        return false;
}

Answer №1

The JSON example provided does not conform to the expected format. It seems to be a result of a copying error, so please review and correct your question. Additionally, it is unclear what specific output you are looking for.

You may find the Array.flat() method handy for flattening nested arrays and extracting values.

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

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

Is it true that textarea is not compatible with AJAX .val() or .text() methods?

I'm attempting to utilize AJAX requests in order to transmit textarea data to a google form, however it appears that .val() isn't functioning correctly with textarea specifically. How can I resolve this issue? My goal is to enable individuals to ...

iOS Safari browser does not support changing the caret color in textarea

Seeking a solution to hide the text cursor (caret) from a textarea on iOS browsers like Safari and Chrome. Despite trying the caret-color property, it does not seem to work. Are there any alternative methods to achieve this? One approach I attempted is b ...

Python 3 encounters issues with mishandling JSON data in a bottle, unlike Python 2

My bottle-based HTTP server mainly deals with shuffling JSON data around. It works perfectly when run in Python 2.7, allowing me to access the JSON data through bottle.request.json in my route handlers. However, when I try running it under Python 3.4, bott ...

The issue with .NET Core - SerializerSettings not taking effect

Configuration.cs services.AddMvc().AddJsonOptions(config => { config.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); DataConverter class JsonConvert.SerializeObject(dataObject) The SerializerSettings ...

Retrieve the chosen option from a dropdown menu and transfer it to the submit button in PHP

I have a unique situation where I need to extract and store selected values from two separate drop-down menus generated from arrays. The goal is to pass these selected values in the submit button link. For example, if a user selects "123" for email and "t ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

What is the proper way to access a variable from another PHP file?

In my index.php file, I have the following code snippet: // Saving the generated JSON to a text file var jsontext = $('#code-output').text(); $.ajax({ url: 'writetxt.php', type: 'POST', data: { data: ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

Updating Angular view based on service parameter change

In-depth Inquiry I have a specific setup with a header view and a main view in my Angular application. The goal is to include a "back" button in the header that should only be visible based on the current page I'm viewing. Actions Taken In my app ...

Breaking down an RxJS observable sequence into various outputs

Can a single observable flux be split into multiple other observables? For example, I have a form that users can submit. The submit action is captured by an observable, and a validator is triggered upon submission. submitAction.forEach(validate) However ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector? <script type="text/html" id="this-content1"> <h1>This Header Info One</h1& ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

If the user fails to respond, Alexa will show an error message indicating that the skill response was marked as a failure

After completing the code for my Alexa skill, I encountered a problem. My fact-based skill template is set to wait for responses after the output, but if Alexa doesn't hear a response within 8 seconds, it generates an error (Skill response was marked ...

Django serving up a blend of HTML templates and JSON responses

Is there a way to render a template in Django and also return a JsonResponse in a single function? return render(request, 'exam_partial_comment.html', {'comments': comments, 'exam_id': exam}) I am attempting to combine this ...

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...

Is it possible to retrieve the value from the searchbar on the server?

I'm seeking assistance on how to retrieve the user-entered value from a search form on my HTML page in my server.js file. I understand that the name/value pair will be cityCode=something, but I'm unsure of the next steps. HTML: <form c ...

Improving JSON encoding functions in PHP version 5.2

There appears to be a bug in JSON encode for php 5.2. Is there a way to resolve this issue without updating my PHP version to 5.3+? If so, how can I do it? Thank you I have identified the problem - it was related to an encoding issue with my string. The ...