Transforming JSON data into a hierarchical tree structure in JSON format

I have a JSON treeData that I need to convert into a different format so that I can use a visualization library in JavaScript.

treeData={
        "leftNode": {
            "leftNode": {
                "leftNode": {
                    "leftNode": {
                        "leftNode": "fence_brand_name = 'reebok'",
                        "rightNode": "fence_brand_id = 123",
                        "centerOperator": "OR"
                    },
                    "rightNode": "fence_category_name = 'shoes'",
                    "centerOperator": "AND"
                },
                "rightNode": "latitude > 19.1140997",
                "centerOperator": "AND"
            },
            "rightNode": "latitude = 72.89498",
            "centerOperator": "AND"
        },
        "rightNode": "radius = 5000",
        "centerOperator": "AND"
    } 

The depth of this tree can vary, and I need to convert it into the following format:

  newTreeData=[{
             leftNode=[{
                  leftNode=[{
                            leftNode="left"
                            rightNode="right",
                            centerOperator="op"
                       }],
                  rightNode="right",
                  centerOperator="op"
             }],
             rightNode="right",
             centerOperator="op"
            }]

I have attempted to convert it using the code below, but I haven't had any success yet.

var addNodes=function(data){
if(isObj(data.leftNode)){
var right=data.rightNode;
var center=data.centerOperator;
    newTreeData.push(rightNode:right,newCenterOperator:center,leftNode:[]);
addNodes(data.leftNode);
   }else{
newTreeData.push(rightNode:data.rightNode,centerOperator:data.centerOperator,leftNode:[]);
   }
}

var function isObj(val) {
 if (val === null) { return false;}
 return ( (typeof val === 'function') || (typeof val === 'object') );
 }

Answer №1

There is no need for that, as you have the option to access the JSON object using Array notation as well, such as:

treeData["leftNode"]["leftNode"]

Alternatively, you can use object notation like so:

treeData.leftNode.leftNode

Furthermore, you can iterate through it, for example:

for (var leftNode in treeData.leftNode) {
    // perform actions on leftNode
}

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

Is there a method in React Native to include the "share" icon in my drawer instead of a button?

How can I add a "share" icon to my drawer? I attempted to insert an icon using <Ionicons name="md-share" size={24} color="black" /> instead of a Button. However, when I do this, the icon is displayed without any title, unlike what I see in the sett ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

obtaining information from newly added form elements in an Angular application

I'm currently working on an app with the MEAN stack. I've managed to dynamically add form elements, but I'm running into an issue where all dynamically added elements are taking the same data when I use ng-model="something.something". What I ...

Tips for effectively dividing a component's code into smaller sub-components

Within my component MyComp, there exists an extensive code that I wish to divide into 3 separate components. In envisioning the structure of MyComp, I am seeking general advice and a brief example in response: import React, { Component, Fragment } from & ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

Design interactive images in NativeScript

I need assistance setting up clickable images in NativeScript. My goal is to arrange 5 images horizontally, and when one image is clicked, the images to its left should change their values. Here's what I've attempted: <Label col="0" row="0" ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

Navigate through chosen options by clicking on a button

It's a new day and I'm facing a simple challenge that seems complicated in the morning haze. I need to create a select dropdown with zoom percentage values, along with + and - buttons to navigate through the list. If I have the following setup: ...

Sending JSON data from the primary window to the secondary window in Electron - A step-by-step guide

I am currently working with a set of 3 files. index.html: ... <a href="#" onclick="fetch(function(data) {console.log(data); subWindow(data)})">subWindow</a> ... The fetch() function retrieves a callback in JSON format. subWindows.js: let m ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

A more concise approach to crafting ajax requests

Lately, I've been immersed in building various web applications using php, mysql, jquery, and bootstrap. Now, I'm faced with a common issue - how to streamline my ajax queries for posting data? Writing code that is not only functional but also a ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

The JSON parameter being sent to the filter function in the Podio API appears to be ineffective

I tried sending a POST request from klipfolio to {app_id}/filter/ with a JSON object specified in the body, but no matter what parameters I include in the JSON object, they don't seem to have any effect. I followed the parameters outlined in the Podio ...

Leveraging Array.map within Angular Interpolation

Is it possible to achieve the following in HTML using Angular 2+? {{ object.array.map((o) => o.property ) }} Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique? ...

What causes certain webpack / Babel ES6 imports without a specified extension to resolve as "undefined"?

When I try to import certain ES6 files (such as .js, .jsx, .ts, .tsx) using the syntax import ComponentName from './folder/ComponentName'; (without extension), they end up resolving as undefined. This occurs even though there are no errors from W ...

Tips on initializing npm run dev as the go-to for launching your app

I need some help with setting up my React project. I am currently running npm run dev in the terminal to compile and run my app. Is there a more efficient way to do this? $ node server/index.js Here is my project folder structure: https://i.sstatic.ne ...

Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being n ...