Converting nested arrays to objects via JSON transformation

I am faced with a nested JSON array structure like this:

 Parent: {
      Child1: [
        {name:'grandchild1', value:'abc', checked:true},
        {name:'grandchild2', value:'pqr', checked:false}
      ],
      Child2: [
        {name:'grandchild3', value:'abcd', checked:false},
        {name:'grandchild4', value:'pqrs', checked:true}
      ],
parent2{...........}....
    };

I am looking to transform it into the following format:

 [  
   {  
      "filename":"Parent",
      "children":[  
         {  
            "filename":"Child1",
            "children":[  
               {  
                  "filename":"grandchild1",
                  "type":"ts"
               },
               {  
                  "filename":"grandchild2",
                  "type":"ts"
               }
            ]
         },
         {  
            "filename":"Child2",
            "children":[  
               {  
                  "filename":"grandchild3",
                  "type":"ts"
               },
               {  
                  "filename":"grandchild4",
                  "type":"ts"
               }
            ]
         }
      ]
   },
   { filename:"Parent1"..........
   },....
]

This structure is needed for an Angular Material tree. You can refer to the sample code provided in this Link

I have attempted to achieve this using the code snippet below:

Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
      const value = obj[key];
      const node = new FileNode();
      node.filename = key;

      if (value != null) {
        if (typeof value === 'object') {
          node.children = this.buildFileTree(value, level + 1);
        } else {
          node.type = value;
        }
      }

      return accumulator.concat(node);
    }, []);
  }

However, the output did not match my requirements.

I would appreciate any suggestions on how to properly convert the structure to the specified format for it to function as intended.

Answer №1

To iterate over objects in JavaScript, you can utilize the for of and for in functions

const list = {Parent1 :{
    Child1: [
      {name:'grandchild1', value:'abc', checked:true},
      {name:'grandchild2', value:'pqr', checked:false}
     ] ,
  Child2: [
   {name:'grandchild3', value:'abcd', checked:false},
   {name:'grandchild4', value:'pqrs', checked:true}
  ]
}, Parent2 :{
    Child1: [
      {name:'grandchild1', value:'abc', checked:true},
      {name:'grandchild2', value:'pqr', checked:false}
     ] ,
  Child2: [
   {name:'grandchild3', value:'abcd', checked:false},
   {name:'grandchild4', value:'pqrs', checked:true}
  ]
}};

const res = []

for(let parent in list){

let parentTemp = {
    filename : parent,
    children : []
}

  for(let child in list[parent]){

      let childTemp = {filename : child, children : []};

      for(let grandChild of list[parent][child]){
          childTemp.children.push({filename : grandChild.name, type : grandChild.value, status: grandChild.checked});
      }
      parentTemp.children.push(childTemp);


  }
  res.push(parentTemp);
}


console.log(res);

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 method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Using cURL for PHP JSON parsing

I am trying to develop a basic webpage that displays the current region based on the user's IP address. To achieve this, I am utilizing an API provided by freegeoip.net. Even though I have successfully configured the code to send the user's IP to ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

Encountering a Jquery TypeError while trying to update the content on

I am currently working on a project where I aim to create a Java Spring application that functions as follows: upon receiving a GET request, the application sends an HTML page with a form. When the form button is clicked, a POST request containing XML cont ...

Understanding the Issue: Newtonsoft.JSON Failing to Deserialize Stringified JSON Schemas

Currently, I am retrieving data from a client that signifies a function within a ChatGPT API request. The detailed documentation can be accessed at: . My assumption was that the JSON received would go through parsing by Newtonsoft.Json, and subsequently, ...

Is there a way to determine if a container is overflowing at the top?

Currently, I am using Puppeteer to scrape Slack. My goal is to confirm whether I have scrolled to the very top of the channel feed. The issue arises because the channel feed does not actually scroll, making it impossible for me to utilize the method outli ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

JavaScript's square bracket notation is commonly used to access nested objects within an object

My goal is to accomplish the following: this.inputs[options.el.find('form').attr('class')] = {}; this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false; Unfortunately, I'm fa ...

Troubleshooting: Difficulty with Angular 2 TypeScript interface array functionality

Currently, I am developing an Angular 2 application where I aim to showcase messages by utilizing an interface and storing all the messages in an array. Below is a snippet of my TypeScript component that highlights this functionality: export class ChatCom ...

Invoke a function within an HTML element inserted using the html() method

Looking for help with a JavaScript function: function toggle_concessions(concessions) { var text = "<table>"+ "<tr><td class='concession-name'>gfhgfbfghfd</td><td class='op-encours&a ...

Issues encountered with invoking function in CodeIgniter controller through Ajax

Running a codeigniter website with an add to cart functionality. When the user clicks the add to cart button, the product is successfully added to the cart after the page reloads. The controller code for this feature is as follows: public function buy($ ...

Retrieving the value of a TextField from Material-UI upon submission

Is it possible to capture the value from a TextField input and display a message conditionally using onSubmit instead of onChange? I have tried implementing this functionality dynamically with onChange, but now I would like to achieve the same result wit ...

Finding numerous keywords in a given text (Javascript)

Here is the code snippet I'm working with: // Finding multiple keywords within a text // Scenario 1 var inputText = "Hello, My name is @Steve, I love @Bill, happy new year!"; var terms = ["steve"]; var result = inputText.toLowerCase().search([terms]) ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

Interfacing my Node.js REST API with AngularJS

I've got angular code that works with a local JSON file: App.controller('bodyController', ['$scope','$http',function($scope,$http){ $http.get('data.json').success(function(data){ $scope.data=data; }).error ...

Retrieve a JSON object by making a request to a URL with specific parameters

Struggling with a common coder's mental block: The idea: Imagine entering a URL like www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345 Rather than receiving a webpage, the goal is to get back a json object for parsing on anoth ...