Transform a flat JSON string into a hierarchical structure by organizing it by parent ID

I am currently working on implementing a Mat-Tree using Angular Material. The data I have is in the form of a flat JSON string:

"Entity": [
  {
      "ID": 1,
      "NAME": "Reports",
      "PARENTID": "0",
      "ISACTIVE": "Y",
      "CREATIONDATE": "2020-03-31T15:08:11",
      "UPDATIONDATE": "2020-03-31T15:08:11",
      "CREATEDBY": 596241,
      "UPDATEDBY": 596241
  },
  {
      "ID": 2,
      "NAME": "TMS - Reports",
      "PARENTID": 1,
      "ISACTIVE": "Y",
      "CREATIONDATE": "2020-03-31T15:08:38",
      "UPDATIONDATE": "2020-03-31T15:08:38",
      "CREATEDBY": 596241,
      "UPDATEDBY": 596241
  },
  {
      "ID": 3,
      "NAME": "TMS - Beneficiary ",
      "PARENTID": 2,
      "ISACTIVE": "Y",
      "CREATIONDATE": "2020-03-31T15:09:34",
      "UPDATIONDATE": "2020-03-31T15:09:34",
      "CREATEDBY": 596241,
      "UPDATEDBY": 596241
  }
]

My goal is to convert this data into Key-value pairs based on their Parent ID relationships. For example:

{
    Reports: 
    {
      'Type 1 Reports': ['Beneficiary Reports', 'Some Other Report'],
      'Type 2 Reports': null //No Children,
    },

    Some Other Menu Items: {
     'My Parent Node': null,
      'Some Other Menu Node': ['Child 1', 'Child 2']
   } 

}

The code snippet I've been using generates a parent-child hierarchy but stores all children in an 'items' array which doesn't work for my needs with Mat-Tree. I want to eliminate the 'Items' array and structure the data as shown above with key-value pairs:

generateTreeData(menuResponse)
{ 
var map = {};
for(var i = 0; i < menuResponse.length; i++){
  var obj = menuResponse[i];
  var parent = '';
  obj.items= [];
  map[obj.ID] = obj;
  if(obj.PARENTID  == "0")
  {
    parent = '-';
  }
  else
  {
    parent = obj.PARENTID;
  }
  if(!map[parent]){
    //Means Parent doesnt exist i.e. node Itself is parent node
      map[parent] = {
         items: []         
        };
  }
   map[parent].items.push(obj);  
}
return map['-'].items;
}

Issue:

The current code structures children nodes within an 'Items' array. I need assistance in restructuring the data into key-value pairs similar to the format mentioned above, extracting only the "NAME" and relevant items from the JSON array. Any suggestions on how to achieve this?

Answer №1

It appears that the expected output structure may not be sufficient if there is a child node for 'Beneficiary Reports'.

Considering the input provided in the question, the ideal output structure should resemble:

{
   "Reports":[
      {
         "TMS - Reports":[
            {
               "TMS - Beneficiary ":[]
            }
         ]
      }
   ]
}

You can refer to this fiddle for more clarity: https://jsfiddle.net/abby_7700/apkgeo1d/3/

var data = [];//please insert your response here
var result = {};
var root = data.find(x => x.PARENTID == 0);
result[root.NAME] = [];

findAndAddChildren(root.ID, result[root.NAME]);
console.log(JSON.stringify(result));

function findAndAddChildren(parentID, collection) {
    var rootChildren = data.filter(x => x.PARENTID == parentID);
    for(var i = 0; i < rootChildren.length; i++) {
    var child = rootChildren[i];
    var temp = {};
    temp[child.NAME] = [];
    collection.push(temp);
    findAndAddChildren(child.ID, temp[child.NAME]);
    }
}

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

What is the best way to filter by enum value in Typescript?

If I define an enum as follows: export enum Status { InProgress = 0, Completed = 1, Cancelled = 2 } and have a class that references the enum: import { Status } from "./Status"; export class TaskDto { public name: string = null; public c ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Identify the category of the component

Using a Link component from version 4.0.0-beta.2, I am exploring its capability to override the root element with a field called component. My goal is to wrap the Link component in a new component called MyLink and pass a custom component through props: ...

Encountering issues while transitioning from Angular 2.0.0-beta.13 to 2.0.0 rc1

I recently upgraded my project from Angular 2.0.0-beta.13 to Angular 2.0.0 rc1, but unfortunately encountered some errors. https://i.sstatic.net/Ofoqi.png Below is a snippet of my source code: package.json ... "dependencies": { "angular ...

JSON.stringify alters the format of a date object

I have a website where users can log in with a specific timezone, regardless of the client-side timezone. When a user selects a date on the website, it is sent to the server side using JSON.stringify along with other properties. However, when the date is r ...

Guide on extracting JSON data from a URL using PHP

As a newcomer to JSON, I have a simple question that I can't seem to find the answer to. I've obtained data in JSON format from an API, but I am having trouble parsing it with PHP. My code snippet is as follows: $opts = array( 'http&apo ...

Is there a way to automatically refresh my environment variables with each monitor run?

I am currently in the process of updating my variables between monitor runs. The goal is to establish communication between collections by utilizing environment variables, where the initial value of the variable is set equal to the most recent variable tha ...

I am unable to retrieve any information from the JSON request

When I send JSON data to a specific route, below is the code I use: const data = [{ name: this.name }] axios .post('/users', { name: this.name }) .then( response => { console.log(response.data); } ) ...

Efficiently extracting data from a JSON dictionary by separating keys and values into individual arrays in Objective C

I'm currently working on accessing currency data from the www.fixer.io API by parsing JSON. I've encountered some challenges trying to extract the keys and values from the "rates" dictionary. It's essential for me to separate them so that I ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Converting text to JSON using JSONP with jQuery's AJAX functionality

Potential Duplicate Question 1 Possible Duplicate Inquiry 2 I have been searching for a definitive explanation on JSONP across various questions but haven't been able to find one yet. For instance, I am attempting to make a cross domain request us ...

Utilizing Angular's intelligent dichotomy of (container) and (presentational) components, integrating conditional logic, and effectively passing inputs throughout the

Imagine you have two simple components, A and B. Component C will only display either component A OR B, which is controlled by smart component D. D (smart) | C (simple) / \ A B (both simple) Both components A and B have 10 inputs each. Ther ...

Transform a row in an ng Smart table to a routerlink using Angular 2

I've been exploring ng2 Smart Table and I'm looking to convert a row (or even cell data) into a clickable link using routerlink. The current method I'm employing to retrieve some of my row's data is as follows: onUserRowSelect(event) ...

Sending JSON data using AJAX in PHP is a common task that many developers

Upon clicking the delete button, the confirmDelete function is called and it posts the parameters as JSON. The response comes back from the server page and enters the success method, but with a blank string value instead of null. I am unable to identify th ...

Issues with the effectiveness of the clarity custom filter in Angular

I'm currently working on a datagrid table that contains a 'status' column. My goal is to create a custom filter that will provide users with a dropdown menu to select specific values. Additionally, I want the column to exclude two values, &a ...

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

A helpful guide on rendering nested maps from JSON data in React.JS

I am attempting to display menu values from a JSON data. This menu has multiple levels, so I am using a nested map function to render the complete menu. const menu = { data:[ { title: "Home", child: [ { title: "SubL ...

Whenever I try to retrieve a value using the key from ModelBindingContext.ValueProvider.GetValue(key

When working with AngularJS to manipulate a complex parent object with different behaviors for its children server-side, I encountered an issue while implementing the CreateModel function as suggested in this answer. The problem arises when any call to bin ...

Challenges of Vue 3 Typescript ComputedRef

I've run into some challenges with Typescript and Vue3. It seems like I might be using Typescript incorrectly in this case. I set up a store using Vue's Composition API. import {computed, reactive} from "vue"; const state = reactive({ ...