Navigating through the various child objects within a JSON structure

As I traverse through a moderately complex JSON object, I gather and store all the values once I reach the end of the recursive loop

Here is an example of the object:

"if": {
    "and": {
        "or": {
            "compare": [
                {
                    "Hello": {
                        "constant": {
                            "string": "1"
                        }
                    },
                },
                {
                    "Hello": {
                        "constant": {
                            "string": "4"
                        }
                    }
                }
            ]
        },
        "before": {
            "Hello2": "12131",
            "Hello": {
                "constant": {
                    "datetime": "2001-01-01T00:00:00"
                }
            }
        }
    }
}

Next, I have defined a function:

function getAllGroups(obj)
{

        for (var k in obj)
        {
            if (k === "hello") {
                counter++;
                array.push([]);
            }
            if (typeof obj[k] == "object" && obj[k] !== null) {
                getAllGroups(obj[k]);
            }
            else
            {
                if (k !== "hello2") {
                    array[array.length - 1].push(obj[k]);
                }
            }

        }
}

It may seem confusing at first, but essentially:

Whenever it encounters the key "hello", a new object is added to the empty array and filled with data. Each time it reaches the key "hello", a new object is created and populated with fresh data.

I faced difficulties in maintaining references to the parent objects. There are specific keys that need to be preserved like "and" & "or". For instance, after reaching the string: 1 which marks the end of the loop, I want to retain that it belongs to "or". Similarly, I wish to indicate that "or" is part of "and". Lastly, the datetime value should be associated with "and". Keep in mind that there can be multiple levels of nested "and" and "or".

EDIT:

I have updated the code to preserve the reference to the parent object. However, it currently only retains the reference to the last parent in the list, resulting in "datetime" being recognized as a child of "and" instead of "or"

function getAllGroups(obj)
{

        for (var k in obj)
        {
            if (k === "and" || k === "or" || k === "not")
            {
                if (parentKey !== "") {
                    array.push([]);
                    array[array.length - 1].push(array[array.length - 1]['parent'] = parentKey);
                    parentKey = k + parentKeyNo;
                    parentKeyNo++;
                    array[array.length - 1].push(array[array.length - 1]['child'] = parentKey);
                }
                else {
                    parentKey = k + parentKeyNo;
                    parentKeyNo++;
                    array.push([]);
                    array[array.length - 1].push(array[array.length - 1]['child'] = parentKey);
                }
            }
            if (k === "Hello") {
                counter++;
                array.push([]);
            }
            if (typeof obj[k] == "object" && obj[k] !== null) {
                getAllGroups(obj[k]);
            }
            else
            {
                if (k !== "Hello2") {
                    if (array[array.length - 1].hasOwnProperty('parent'))
                    {
                        array[array.length - 1].push(obj[k]);
                    }
                    else
                    {
                        array[array.length - 1].push(array[array.length - 1]['parent'] = parentKey);
                        array[array.length - 1].push(obj[k]);
                    }

                }
            }

        }
}

DESIRED OUTPUT:

[
    [
        {
            "child": "and"
        }
    ],
    [
        {
            "parent": "and"
        },
        {
            "child": "or"
        }
    ],
    [
        {
            "parent": "or"
        },
        {
            "string": "1"
        }
    ],
    [
        {
            "parent": "or"
        },
        {
            "string": "4"
        }
    ],
    [
        {
            "parent": "and"
        },
        {
            "datetime": "2001-01-01T00:00:00"
        }
    ]
]

Answer №1

Below is the code where you can manage your key and value using the process() function:

var jsonObject = {
  "if": {
    "and": {
      "or": {
        "compare": [{
          "Greetings": {
            "constant": {
              "string": "1"
            }
          },
        }, {
          "Greetings": {
            "constant": {
              "string": "4"
            }
          }
        }]
      },
      "before": {
        "Greetings": {
          "constant": {
            "datetime": "2001-01-01T00:00:00"
          }
        }
      }
    }
  }
};

// storing values of 'Greetings' key
var greetingValues = [];

function process(key, value) {
  console.log(key + " : " + value);
  if (key == 'Greetings') greetingValues.push(value);
}

function traverse(obj, func) {
  for (var prop in obj) {
    func.apply(this, [prop, obj[prop]]);
    if (obj[prop] !== null && typeof(obj[prop]) == "object") {
      // traversing deeper into the object tree
      traverse(obj[prop], func);
    }
  }
}

traverse(jsonObject, process);
alert(greetingValues.length);

I hope this solution proves to be useful.

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

JavaScript calculator not calculating values correctly

I am facing an issue with my JavaScript calculator. The problem occurs when I try to perform addition, such as adding 5+5, the result gets stuck at 10 and does not continue to increment (10, 15, 20, etc). Below is the code snippet that I am using: func ...

How to Remove a Dynamically Generated Popover in Angular

As a newcomer to angular, I successfully implemented a bootstrap popover around selected text using the following function: $scope.highlight = function () { var a = document.createElement("a"); a.setAttribute('tabindex', "0"); ...

Ways to retrieve an element from an array

I need help finding the right way to retrieve the value of the message "Meeting 9943...is not found or has expired". Here's what I tried: if (response.data.status == 404) { angular.element(document.getElementById("msg")).css("color", "red"); ...

I'm having trouble showing the concealed list with JavaScript

I am new to javascript and facing a challenge. Whenever I update the list items in an HTML example from engineer, pilot, technician, if I select engineer, there should be an onchange event calling a function in JavaScript that shows a hidden select list co ...

PHP: When arrays are stored within another array, it appears that duplicates are being generated

I have been struggling to find a straight answer to this seemingly basic question. From what I understand, storing an object in an array should store a reference, not a copy. This means that any changes made to the object should be reflected when accessed ...

Consistent surface appearance across combined mesh

Is there a way to texture a merged mesh from geometry as one solid piece rather than separately on each individual shape? In the provided code snippet, the textures are applied to separate geometries (refer to image points 1 and 2) - two Cubes and one Cyli ...

Is there a way to utilize a MongoDB plugin to retrieve results directly as a return value instead of within a callback function?

I came across a MongoDB plugin for Node.js that always utilizes callback functions to return search results. However, I am looking for a way to receive the result directly without using callbacks. The code snippet below does not provide me with the desire ...

Is there a way to have the JavaScriptSerializer automatically execute a constructor/method/any other operation to set initial values after deserialization?

Exploring JSON and the .Net JavascriptSerializer is proving to be a fun learning experience. Here's my current code: JavaScriptSerializer serializer = new JavaScriptSerializer(); myObject = serializer.Deserialize<MyObje ...

Storing information in an array and converting it to JSON using dual nested foreach loops in PHP

I need to retrieve data from two tables that have no relation. I am using a foreach loop to fetch all the data by a selected key and combine the data from both tables into an array. How can I store the data in an array while fetching data from two tables u ...

JQ alongside Windows Batch - failure in selection

Having trouble using a Windows batch file with JQ and attempting to pipe the select filter. An Example Json that is being parsed with JQ: { "name": "test-mmc-deploy", "id": "local$3d2075c5-73c0-47aa-8df5-cee3a70f68c4", "lastModified": "Mon, 1 May 2 ...

The initial ajax request successfully connects to the file, but encounters a 404 error upon the second attempt

I am currently encountering an issue with a jQuery post function. The function is designed to run multiple times and then stop, which it has successfully done in the past. However, now the problem arises when the function tries to execute itself again afte ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

The mobile navigation in HTML has a slight issue with the ::after pseudo-element, specifically within the

As I prepare to launch my website, I have made adjustments to the mobile layout by moving the navigation links to a navigation drawer. The template I am using included JavaScript scripts to handle this navigation change. However, I encountered an issue whe ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Exploring the efficiency of including arrays in PHP

How will the performance of "header.php" be impacted if I include a large PHP array? For instance, if I have a 1GB PHP array in a file called "data.php" that looks like $data = array( //1GB of data ) What type of performance hit can I expect when I inclu ...

"Converting a JSON bundle to a JSON object on an Android device: A step

Hey there! I've recently integrated Paytm Wallet into my App and I'm receiving the response in JSON format as a Bundle object. The challenge now is to extract details like ORDERID, TXNAMNT, etc. from this JSON bundle. Is there a specific method t ...

The plugin's element is not compatible with jQuery methods

This particular plugin is designed to enhance the appearance of checkbox inputs. It creates a more visually appealing version of standard checkboxes. However, I have encountered an issue with one of the variables in the code. Let's discuss the theLab ...

The functionality to generate forms on the click of a button appears to be malfunctioning

I am currently attempting to dynamically create Bootstrap Panels using an `onclick` function. However, I want each Panel to generate multiple forms when the button is clicked. In my current code, the first Panel successfully creates forms when the button i ...

Develop an array of JSON Objects within a Java environment

My task involves handling a CSV file with 10 columns and multiple rows. The goal is to convert each row into a JSON object. An example of the file structure is as follows: Name, Age, Address..........and other columns ABCD, 23 , HOME.............and other ...

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...