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

What's causing the Python Segfault, could it be related to the

I have been working on generating prime numbers less than 2000000 and calculating their sum. Initially, I attempted to find prime numbers up to 40000 but encountered a Segmentation Fault error. After multiple attempts, I determined that the program crashes ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

Understanding the readability of JavaScript arrays.ORDeciphering

Recently, I've been working with a JSON OBJECT that looks something like this { "kay1": "value1", "key2": "value2", "key3":{ "key31": "value31", "key32": "value32", "key33": "value33" } } However, I am interested in converting it ...

Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code: <v-btn @click="setSelectedTab('Set') "> ... <component :is="selectedTab"></component> ...

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

How to Efficiently Organize OpenAI AI Responses Using TypeScript/JavaScript and CSS

I'm using a Next.js framework to connect to the OpenAI API, and I've integrated it seamlessly with an AI npm package. The functionality is incredible, but I've encountered an issue regarding line breaks in the responses. You can find the AI ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

Error encountered in 11ty: Invalid operation - eleventyConfig.addPassthroughCopy is not a recognized function

Attempting to integrate my CSS and JavaScript codes into 11ty has been a bit challenging for me. I recently discovered that 11ty utilizes something called .11ty.js, so I decided to utilize the addPassthroughCopy() function. Below is the script I tried: mo ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

Guide on converting JSON encoded data into a JavaScript array

I have a few web pages that display results in the following format: [{"id":"1","company":"Gaurishankar","bus_no":"JHA 12 KH 1230"}, {"id":"2","company":"Gaurishankar","bus_no":"BA 2 KH 2270"}] Now, I want to take this JSON encoded data and use it in a J ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

ReactJS is unable to locate a valid DOM element within the target container

I recently embarked on my journey to learn ReactJS and I celebrated successfully writing my first code. However, when I encountered the same pattern with components, an error popped up stating _Invariant Violation: registerComponent(...): Target container ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...