Form a tree structure using a compressed object

I’m struggling with a specific issue: I have an object structured like this:

Object {
   id: string;
   parentId: string;
}

What I’m aiming for is a nested object structure like this:

NestedObject {
id: string;
parentId: string;
children: [
    {
      id: 62,
      parentId: 74,
      children: [{ id: 56, parentId: 62 }, { id: 63, parentId: 62 }],
    }
}

The function I came up with returns a somewhat nested object, but it's not exactly what I need. I’m having trouble pinpointing the issue. Can anyone help me identify where the problem might be? Thank you.

function list_to_tree(arr: any[]) { 
 const tree = {
        root: {
            id: "root",
            children: []
        }

    }

    arr.forEach(item => {
        tree[item.id] = {
            ...item,
            children: []
        }
    })

 

    Object.values(tree).forEach(item => {
        if (item.parentId) {
            tree[item.parentId].children.push(item)
            const i = tree[item.parentId]
            tree.root.children.push(i)
        }

    })

    

    return tree.root

}

Answer №1

One efficient method is to store all references to `id` and `parentId` in an object, eliminating the need to search for parent nodes.

This technique allows for the creation of a tree structure independently of the order in which the data is provided.

Once all nodes have been traversed, the tree is fully constructed.

const
    data = [{ id: 4, parentId: null }, { id: 12, parentId: 133  }, { id: 3, parentId: 4 }, { id: 67, parentId: 98 }, { id: 23, parentId: 3 }, { id: 7, parentId: null }, { id: 134, parentId: 7 }, { id: 3512, parentId: 23 }, { id: 98, parentId: null }, { id: 133, parentId: 23 }],
    tree = function (data, root) {
        const t = {};
        data.forEach(o => {
            Object.assign(t[o.id] = t[o.id] || { id: undefined, parentId: undefined }, o);
            t[o.parentId] ??= {};
            (t[o.parentId].children ??= []).push(t[o.id]);
        });
        return t[root].children;
    }(data, null);

console.log(tree);
.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

Searching for JSON data in JavaScript

Is there a more efficient approach for searching data in JSON other than using loops? This is specifically for editing and deleting purposes. for(var k in objJsonResp) { if (objJsonResp[k].txtId == id) { if (action == 'delete') { obj ...

Using AJAX to Post Data with Relative Path in ASP.NET MVC 5

I have been developing an MVC 5 web application that utilizes AJAX Posts to invoke Controller Actions. For example, I have a controller named "Account" with an action called "Create". In my Account/Index view, which is rendered by accessing an Account/Ind ...

How can I transform each word to resemble this format?

let sentence = "Hello+world + like+ this + name,bla"; sentence = sentence.replace(/\+\s\+/g, function(match){ return "*" + match.trim() + "*"; }); alert(sentence); // Output will be " *Hello*+*world*+like*+this*+name,*bla* "; How can I ...

An issue arises in vue.js where the v class binding takes precedence over other bindings and fails to properly remove

I have a game with a punching bag where I want to incorporate an animation class each time the bag is clicked. Once the health meter hits zero, I intend to replace the bag image with one depicting a burst bag. Things are running smoothly up until the poin ...

Error: The array's property is not defined

I am currently working on a visualization tool for sorting algorithms, but I keep encountering an error that says "Cannot read properties of undefined (reading 'map')" in line let bars = this.state.array.map((value, index) =>. You can find my ...

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

Combining React, Express, and Nodemailer poses challenges in rendering components and sending emails simultaneously

Looking to utilize client-side routing for my React app and also incorporate Nodemailer for sending emails. However, since Nodemailer cannot be used on the client-side, I need to implement it on the Express server. Here is how the server code looks like: ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Utilize jQuery to transform array values into date objects

I am receiving an array from a .net controller. The values I am getting for dates are: /Date(1445256000000)/ and /Date(1445256900000)/ Instead of this, I need to convert these into proper date values. Now that I have an array of objects, I want to upda ...

Invoking a function from a collection of mixed data types

I have established a mapping for a discriminated union consisting of different types, each linked to a corresponding function that uses a member of the union as a parameter: export interface Truncate { type: 'truncate' maxLength: number } ex ...

Modifying SVG gradients with JavaScript

My goal is to modify the stop color of a gradient displayed in an SVG element. I've been trying to adjust the stop-color attribute, but so far, my attempts have not been successful: <svg><defs> <linearGradient gradientTransform="rotat ...

Looping in jQuery: Tips for Improving Performance

In my popup window, I have a JavaScript function that utilizes jQuery to retrieve checked checkboxes from the parent window. It then uses jQuery again to access associated data from hidden fields in the parent window for each checkbox. var chked = $(&apos ...

What sets apart a post API call from form submission using the post method?

Is it possible to call the payment gateway from Node.js using a POST API call? I understand that traditionally the payment gateway is called through form submission with the method set as post, which redirects to a new page. However, if I use a POST API ...

Using Angular 2/4/5 to Bind UTC-formatted Date to Datepicker

As someone who is just starting out with Angular and Angular Material, I have encountered an issue regarding zonedDate format for dates in my backend. The backend requires dates to be in zonedDate Format like this: 2018-04-11T02:12:04.455Z[UTC]. However, ...

What is the definition of the term "WebapiError"?

I'm currently developing a Spotify Web App that focuses on retrieving the top albums of KD Rusha using the Client ID and Artist ID to exclusively fetch his releases on Spotify. To accomplish this, I am utilizing an npm package called spotify-web-api-n ...

Top method for identifying genuine users and preventing bots

Utilizing a Maps API can be costly, especially with the fees per request To minimize requests, I heavily rely on caching techniques The API is invoked on every pageload, but unnecessary for non-human users like googlebot What would be the most effective ...

Error encountered with Angular JS Express JS File Upload: "undefined is not a function"

There seems to be an error displaying in the console: TypeError: undefined is not a function at C:\nodefiles\new\server.js:101:16 at Layer.handle [as handle_request] (C:\nodefiles\new\node_modules\express\li ...

When the child content surpasses the height of the parent, you can scroll within an overflow:visible; div

My sidebar navigation menu includes children and sub-children that are revealed on hover. You can view a simplified version of it in this jsfiddle link: https://jsfiddle.net/s096zfpd/ Although the example provided is basic, my main concern arises when the ...

Remove an item from the options list in the select2 plugin after an event occurs

I am currently using the Select2 plugin in my project and I am facing an issue where I want to remove an option from the main list. However, when I click on the "x" button generated by the code, it only removes it temporarily from the plugin's list. U ...

What action is initiated when the save button is clicked in ckEditor?

Incorporating a ckeditor editor into my asp.net application has been successful. At this point, I am looking to identify the event that is fired by ckeditor when the save button in the toolbar is clicked. Has anyone come across this information? ...