Recursively transform JSON tree node elements into a single, cohesive JSON format

Seeking assistance with converting this JSON tree nodes into the final JSON structure by recursively joining the nodes. Any help would be greatly appreciated. I require a recursive function in JavaScript. Provided below is the sample input and the desired output. Input

{
  root: {
    parent_id: 'root',
    current_id: 'root',
    children: ['node_233443'],
    type: 'stack',
  },
  node_233443: {
    parent_id: 'root',
    current_id: 'node_233443',
    children: ['node_fdfd33', 'node_hd44d4'],
    type: 'column',
  },
  node_fdfd33: {
    parent_id: 'node_233443',
    current_id: 'node_fdfd33',
    children: [],
    type: 'text',
  },
  node_hd44d4: {
    parent_id: 'node_233443',
    current_id: 'node_hd44d4',
    children: [],
    type: 'image',
  },
};

Desired Output

{
  parent_id: 'root',
  current_id: 'root',
  children: [{
    parent_id: 'root',
    current_id: 'node_233443',
    children: [{
      parent_id: 'node_233443',
      current_id: 'node_fdfd33',
      children: [],
      type: 'text',
    },
    {
      parent_id: 'node_233443',
      current_id: 'node_hd44d4',
      children: [],
      type: 'image',
    }],
    type: 'column',
  }],
  type: 'stack',
}

This is the solution I have come up with.

const clonedNodes = structuredClone(nodes);

const recurse = (json) => {
  json.children = json.children.map((item) => {
    if(clonedNodes[item]) {
      return recurse(clonedNodes[item])
    }
  }, [])
  return json;
}

console.log(recurse(clonedNodes.root), nodes)

If you have any suggestions for improvement, please share them. Thank you.

Answer №1

To create a nested structure from your data, you can associate the objects in the `children` arrays with their corresponding identifiers. It's important to duplicate your original object to prevent any unwanted changes:

function createNestedObject(data) {
    const clone = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, {...value}]));
    for (const node of Object.values(clone)) {
        node.children = node.children.map(id => clone[id]); 
    }
    return clone.root;
}

const inputData = {root: {parent_id: 'root',current_id: 'root',children: ['node_233443'],type: 'stack',},node_233443: {parent_id: 'root',current_id: 'node_233443',children: ['node_fdfd33', 'node_hd44d4'],type: 'column',},node_fdfd33: {parent_id: 'node_233443',current_id: 'node_fdfd33',children: [],type: 'text',},node_hd44d4: {parent_id: 'node_233443',current_id: 'node_hd44d4',children: [],type: 'image',},};
const resultData = createNestedObject(inputData);
console.log(resultData);

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 with word wrap and pattern attributes on my website

I'm currently in the process of developing a website and I've implemented the jQuery autocomplete feature. My main goal is to ensure that long words, longer than the input field itself, either break into the next line or allow users to manually b ...

Troubleshooting problems with manipulating arrays within JSON using the map function

I'm currently working on a project to create a Pokemon wiki-style webpage as a beginner project. I'm trying to display the types of each Pokemon using the JSON object retrieved via axios. However, I'm encountering issues with using the map m ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Ways to extract the ASP.net variable value and place it inside a JavaScript textbox

Currently, I'm in the process of developing Javascript code for an ASP.net page. Within my coding framework, the string "foo" is linked to a string variable called myString. In order to transfer the value of myString to a JavaScript variable, I incl ...

The naming convention for fields in a JSON result within a WebAPI environment

1) I am facing an issue with a WebAPI method that returns an object User. The fields of this object in the callback of the ajax call all start with uppercase letters. I want to convert them to camelCase in the result without having to manually add [JsonPro ...

A guide to triggering AlertIOS in React Native

As an iOS developer with limited knowledge of javascript, I am currently attempting to utilize the AlertIOS function. The provided document API for AlertIOS is as follows: static alert(title: string, message?: string, buttons?: Array<{ text: ?string; on ...

Guide to implementing Apollo GraphQL subscriptions in NextJS on the client-side

As a newcomer to NextJS, I am facing the challenge of displaying real-time data fetched from a Hasura GraphQL backend on a page. In previous non-NextJS applications, I successfully utilized GraphQL subscriptions with the Apollo client library which levera ...

issue with taffydb update functionality

Struggling to make changes to an existing record within a TAFFY database. Initially, I insert a single record and proceed to update it. However, the update process fails to execute. var cSheetXref = TAFFY(); cSheetXref.insert({ "ID":0, "vendor":"", ...

"Instead of sending JSON to the AJAX jQuery request, the PHP `json_encode` function is used

Creating a simple contact form as a WordPress plugin, I have developed a form as a popup within the same page: <form method="post" id="w_form" enctype="multipart/form-data"> <label for="first_name" class="text-secondary">First Name</la ...

jquery mobile web app displays blank space at the bottom of the page

Currently, my web app (developed using JQM) is customized for iPhone. Despite all elements being adjusted to fit the page height, I am experiencing an issue with white space appearing at the bottom of the page. When viewed on a PC browser, everything look ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

I keep receiving a JavaScript alert message saying "undefined."

When I try to alert the item_id after giving input in the quantity textbox, I am receiving an undefined JavaScript alert. The code snippet below is not displaying the alert as expected: var item_id=$("#item_"+i).val();alert(item_id); In addition, my mode ...

Trouble invoking npm package.json scripts

The package.json file in my projects directory contains the following scripts section: "scripts": { "seed": "node bin/seed", "test": "echo \"Error: no test specified\" && exit 1" }, Executing $ npm test results in the followin ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Draggable Table Columns with HTML, CSS, and JavaScript

My goal is to create a table in a JSP page that functions similarly to the example shown here. I would like to be able to drag a column of dates within the table and have a form pop up. Can anyone provide guidance on how I can achieve this in JSP? ...

Developing a model in NodeJS poses a challenge for me

While attempting to create a model in NodeJS const mongoose = require ('mongoose'); const User = mongoose.model('User',{ name:{ type:string }, lastname:{ type:string }, age: { type:Number } }) module.exports = User; **errorIS ** C: ...

What is the best way to switch to a different page in NextJs without causing a full page reload?

In my observation of NextJs, I've noticed that when clicking on a <Link> to navigate to another page, the getInitialProps function is called even if it's the same page being visited. For example, on the /profile page, there are two compone ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

I have a particular scenario in mind and I am looking for the desired outcome using jQuery

I attempted a similar approach to this code snippet but did not achieve the intended result: $('div').contents().filter(function() { return this.nodeType === 3; }).wrap( '<p></p>' ).end().filter( 'br' ).remove(); ...

Angular's observables were unable to be subscribed to in either the constructor or ngOnInit() functions

Currently, I am incorporating an observable concept into my application. In this setup, a service is called by component1 to emit an event that is then subscribed to by component 2. Below is the code snippet for reference: Service Code export class Mes ...