Craft a hierarchical JSON structure out of a different nested JSON object [PAUSE]

Looking to transform an existing JSON object into a new object structure.

Here is the current JSON object:

{
  "name": "Parent",
  "children": [
      {
          "name": "Child1",
          "children": [
              {
                  "name": "GrandChid1",
                  "children": []
              },
              {
                  "name": "GrandChild2",
                  "children": []
              },
              {
                  "name": "GrandChild3",
                  "children": [
                      {
                          "name": "GrandGrandChild1",
                          "children": [
                              {
                                  "name": "GrandGrandGrandChild1",
                                  "children": []
                              },
                              {
                                  "name": "GrandGrandGrandChild2",
                                  "children": []
                              }
                          ]
                      }
                  ]
              }
          ]
      }
  ]
}

The desired new object structure:

{
  "Parent": [
      {
          "Child1": [
              {
                  "GrandChid1": ''
              },
              {
                  "GrandChild2": ''
              },
              {
                  "GrandChild3": [
                      {
                          "GrandGrandChild1": [
                              {
                                  "GrandGrandGrandChild1": ''
                              },
                              {
                                  "GrandGrandGrandChild2": ''
                              }
                          ]
                      }
                  ]
              }
          ]
      }
  ]
}

In case there are no children, the object value becomes a string (key-value pair). A recursive solution is sought for this task, any assistance is appreciated.

Answer №1

Attempt

let transform = obj => (obj.children = obj.children.map(child => transform(child)),
             {[obj.name]: obj.children.length ? obj.children:''});

let data= {
  "name": "Parent",
  "children": [
      {
          "name": "Child1",
          "children": [
              {
                  "name": "GrandChid1",
                  "children": []
              },
              {
                  "name": "GrandChild2",
                  "children": []
              },
              {
                  "name": "GrandChild3",
                  "children": [
                      {
                          "name": "GrandGrandChild1",
                          "children": [
                              {
                                  "name": "GrandGrandGrandChild1",
                                  "children": []
                              },
                              {
                                  "name": "GrandGrandGrandChild2",
                                  "children": []
                              }
                          ]
                      }
                  ]
              }
          ]
      }
  ]
}

let transform = obj => (obj.children = obj.children.map(child => transform(child)),{[obj.name]: obj.children.length ? obj.children:''});

console.log(transform(data));

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

Production environment experiences issues with Angular animations

In my MEAN stack application, I started with Sails.js. Everything was working smoothly during development, especially with angular-animate. However, once I changed the Sails environment to production, I encountered issues. Grunt is set up to concatenate a ...

What is the best way to utilize this resulting value as an input?

I am trying to generate a random number using math.random and use that value in the following script: let bday = Math.floor( Math.random() * (30 - 1 + 1) + 1 ); await test.page.select('select[name="day_select"]',bday); However, I am ...

Develop a design utilizing a foundational database entity

I'm new to AngularJS and I am seeking guidance on how to properly separate the model from the controller. In my previous experience, I have always integrated models within the controllers. For example: angular.module("app").controller("customerContr ...

Transform ABAP information into an iXML object, showcasing it in JSON-XML layout

Is there a more efficient way to read arbitrary ABAP data into an iXML document object containing the JSON-XML representation? The current method involves a double application of the id transformation, which may not be very efficient. Is there a more dire ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Preventing a user from navigating away from a page without completing a specific action, such as clicking a submit button

I am in the process of developing an interactive quiz platform. The quiz includes a timer that begins counting down once the user initiates the quiz. Upon completing the quiz, the user is expected to submit their answers. If the user runs out of time, th ...

Unlike other templating engines, EJS does not automatically escape characters

In my current project, I am utilizing a Node JS server to query MongoDB and then display the results in an EJS template using the code snippet: res.render('graphFabric.ejs', {'iBeacons':[(beacon)]});. However, when attempting to re ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

Unable to modify $scope value within the directive

This special function triggers once ng-repeat is done iterating through the list using scope.$last: simpleSearchApp.directive('afterResults', function($document) { return function(scope, element, attrs) { if (scope.$last){ scope.windowHe ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

Navigating JSON data with NewtonSoft's parser

There is a large number of messages in my JSON file, totaling over 6,300. The JSON structure looks something like this... { "messages":[ { "id": ... } ... ]} I am attempting to iterate through each message within this JSON file using NewtonSoft a ...

Tips for combining a select option and search field into a seamless integrated feature

I'm looking to implement a search field in my project that includes the ability to select specific parameters before running the search. I want it to have a seamless design similar to the image shown below. https://i.sstatic.net/niWP8.png Although I ...

Retrieve the component information from the JavaScript function located outside of the main code

Is there a way to retrieve the component data using an external JavaScript function? I am looking to access markers, labels, and images. Vue.component('home', { template: '#home', data: () => ({ markers: [ ...

jQuery is unable to locate the FireBreath object

Currently, I am in the process of developing a web video player by using Firebreath to compile my C/C++ codec as a browser plugin. The plugin has been successfully loaded and is functioning properly (start, stop video, etc.). My next goal is to enable full ...

Using the $timeout function inside an AngularJS factory

In my project, I decided to utilize an AngularJS factory to create new instance models. Each model includes a progress value that is manipulated based on user actions such as "start", "pause", and "stop". app.factory('ModelA', ['$timeout&ap ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

What is the best way to render a view, hide parameters from the URL, and pass data simultaneously?

In order to display the current view: statVars["sessions"] = userSessions; res.render("statsSessions", statVars); Nevertheless, I must find a way to hide the URL parameters from showing up in the browser's address bar (these parameters are sourced ...

When you use Greasemonkey to click a link embedded within the content

In need of assistance with clicking a dynamic link using Greasemonkey. The only static part of the code is the text 'Attack This Player'. The href attribute of the link changes depending on the page. Here is my current code: function click_elem ...