Recursively converting trees in JS/ES6

Currently, I am attempting to convert a tree structure provided in the following format:

{"Parent": 
    {
    "Child1": ["toy1"],
    "Child2": 
          {
              "Nephew": ["toy2", "toy3"]
          }
    }
}


into a standardized tree format like this:

{
"name": "root",
"children": 
    [{"name":"Parent",
      "children": 
          [{
          "name":"Child1",
          "children": ["toy1"]
          },
          {
          "name":"Child2"
          "children": 
              [{
              "name":"Nephew",
              "children": ["toy2", "toy3"]
              }]
          }]
    }]
}


Essentially, my goal is to normalize the tree structure. I have attempted this using the code below:

function recurse(elem) {
    if (typeof(elem) !== "object") return elem;
    level = [];
    for (let part in elem) {
        level.push({
            name: part,
            children: recurse(elem[part])
        });
        console.log(level);
    }
    return level;
}
restrucTree = {
    name: "root",
    children: recurse(tree)
};

However, it seems that there are some issues with the recursion and object construction as the root node (in this case "Parent") is missing from the transformed tree. Additionally, this method fails when the tree branches out into multiple sub-trees, only recognizing the last one. My assumption is that during the recursive stack unwinding, stored objects are being lost, but I can't figure out how to address this problem. If you have any insights on where these errors may be originating from, I would greatly appreciate your input!

Answer №1

Another approach is to use recursion to iterate through all keys, constructing new objects and choosing either an array or an object for the next recursive step.

function createObject(object) {
    return Array.isArray(object)
        ? object
        : Object.keys(object).map(function (key) {
            return { name: key, children: createObject(object[key]) };
        });
}

var data = { Parent: { Child1: ["toy1"], Child2: { Nephew: ["toy2", "toy3"] } } },
    result = { name: 'root', children: createObject(data) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Having trouble displaying images using ejs.renderfile

I've been struggling to generate a PDF from an EJS file with the image rendering correctly. Here is my setup: My app.js code snippet: let express = require("express"); let app = express(); let ejs = require("ejs"); let pdf = require("html-pdf"); let ...

Tips on allowing a rectangle to be draggable using HTML5

I have been experimenting with resizable and draggable rectangles in HTML5. I've managed to create resizable rectangles, but I am having trouble getting them to drag using mouse events. You can view my JSFiddle code at the following link: here. / ...

Is there a way to extract information from my JSON file and display it on my website?

My aim is to populate my HTML page with data from a JSON file. Approach I created a JavaScript file: update-info.js In this file, I used an AJAX call to retrieve data from my JSON file data.json If the request is successful, I utilized jQuery's .htm ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Error message: "Receiving a 'TypeError' in Node.js async parallel - the task is not recognized as a

Currently, I am utilizing the async module to run multiple tasks simultaneously. In essence, I have two distinct files named dashboard.js and Run.js. Dashboard.js module.exports = { func1 : function(){ console.log(“Function one”); }, ...

Create an interactive list with the ability to be edited using HTML and

I'm currently working on a UI scenario that involves a text box field with two buttons beneath it. When the user clicks the first button, a popup will appear prompting them to input an IP address. Upon submitting the IP address in the popup, it will b ...

I encountered an issue where I am unable to subtract from jQuery's .outerHeight() within an if statement

I've been working on creating an ajax request that triggers when a div is scrolled to the bottom. I thought I had it figured out with this code, but I've run into an issue. Everything works fine without subtracting 100 from the elem.outerHeight() ...

Functionality Issue: Submit Button Not Working on Designed Form Select

Through dedication and hard work, I managed to create a customized form with images that display correctly in Firefox, Chrome, and Internet Explorer's compatibility mode. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

Issue with HighCharts: Bar columns not extending to the x-Axis when drilling up

I am encountering an issue with HighChart/HighStock that I need help with. To illustrate my problem, I have set up a JSFiddle. The problem arises when a user drills down on a bar column, causing the y-axis to shrink and consequently making the x-axis appea ...

Testing an Angular factory that relies on dependencies using JasmineJS

I have a factory setup like this: angular.module("myServices") .factory("$service1", ["$rootScope", "$service2", function($rootScope, $service2){...})]; Now I'm attempting to test it, but simply injecting $service1 is resulting in an &ap ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

Determining the browser width's pixel value to enhance responsiveness in design

Lately, I've been delving into the world of responsive design and trying to grasp the most effective strategies. From what I've gathered, focusing on content-driven breakpoints rather than device-specific ones is key. One thing that would greatl ...

Discover automatically generated titles for dynamic hyperlinks

I am looking to generate dynamic links for a collection of documents with varying names, such as Test, Test2, and so on. I want the link text to display as "Document TestN," where N is the specific document number. Currently, I am able to create the links ...

Modeling a versatile user system in Mongoose for various user types

I am in the process of creating a unique social networking platform for students and teachers using the MEAN stack. Each student will have their own distinct account page separate from the teachers. There is only one registration page where both teachers ...

Encountering issues with AngularJS number filter when integrating it with UI grid

When using the angularjs number filter in angular-ui-grid, I am facing an issue. The filter works perfectly fine within the grid, but when I export the grid to csv and open it in Excel, the formatting is not maintained. I have included the filter in the e ...

Transferring the chosen dropdown value to the following page

I am attempting to transfer the currently selected value from a dropdown to the next page using an HTTP request, so that the selected value is included in the URL of the subsequent page. The form dropdown element appears as follows: <form name="sortby ...

Ways to turn off default browser tooltip using bootstrap4 tooltip

Check out the code below, which demonstrates displaying both the bootstrap tooltip and the native title-attribute tooltip: This is an example of text with a tooltip using Font Awesome icon: <i class="far fa-question-circle" data-toggle="tooltip" title= ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

What is the proper way to showcase thumbnails in different sizes?

Currently, this is what I have: https://i.sstatic.net/VOC2z.png The display looks optimal with high-resolution landscape photos. This is the HTML and CSS code in use: <div class="upload-thumb ng-scope visible"> <span class="delete-media"&g ...

Having trouble configuring and executing Vue.js within Laravel

I am fairly new to vue.js but I have experience with laravel. With the recent release of laravel 5.3, I decided to try running a sample application using Vue. resources/js/app.js : /** * First we will load all JavaScript dependencies for this pr ...