Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array:

type Tree = {
  id: number;
  name: string;
  email: string;
  children: Tree[];
};

const tree: Tree[] = [
  {
    id: 1,
    name: 'Truck',
    email: '@mail',
    children: [
      {
        id: 11,
        name: 'Car',
        email: '@mail',
        children: [],
      },
    ],
  },
  {
    id: 2,
    name: 'Bus',
    email: '@mail',
    children: [],
  },
];

There are 3 modifications I need to make to this array:

  1. change the property key 'id' to 'userId'
  2. change the id type from number to string
  3. remove the email property

so the new output will adhere to this type:

type NewTree = {
  userId: string;
  name: string;
  children: NewTree[];
};

// output of the new tree
const newTree: NewTree[] = [
  {
    userId: '1',
    name: 'Truck',
    children: [
      {
        userId: '11',
        name: 'Car',
        children: [],
      },
    ],
  },
  {
    userId: '2',
    name: 'Bus'
    children: [],
  },
];

This is my current implementation

const restructuredTree = (tree: any[]) => {
  for (const node in tree) {
    const { id: userId, name, children } = tree[node];
    restructuredTree(children);
    tree[node] = { userId, name, children };
  }
};

I'm unsure where to place a return statement, and when I return "tree[node] = { userId, name, children };", it only affects one level deep.

Answer №1

To extract specific properties like id, name, and children from an array of objects, you can utilize the .map() method along with destructuring. By iterating through each object in the array, you can create a new object that reconstructs the structure based on the desired properties while recursively applying the same process to any child arrays. This recursive function continues until it encounters an object with an empty children array, serving as the base case to stop the recursion:

const tree = [ { id: 1, name: 'Truck', email: '@mail', children: [ { id: 11, name: 'Car', email: '@mail', children: [], }, ], }, { id: 2, name: 'Bus', email: '@mail', children: [], }, ];

const getNewTree = (tree) => tree.map(({id, name, children}) => ({
  userId: String(id),
  name,
  children: getNewTree(children)
})); 
console.log(getNewTree(tree));

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

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

Introduce a fresh parameter into the promise all chain

I am using the code below and it is functioning as expected. However, I now need to incorporate the modifyOpt() function. Currently, the code works and returns args[2] but I also need to include another step... I want to pass the return value (port) from ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive: @Directive({ selector: '[myRequired][ngControl ...

What is a method to omit elements within a nested child element from a selection without relying on the children() function

Here is an example of an element: <div id="foo"> <a href="#" class="some">click me</a> <div id="bar"> <a href="#" class="some">click me too</a> </div> </div> I am facing the challenge of selectin ...

It is not possible to upload files larger than 4mb in ASP.NET MVC3

I am facing an issue with uploading files in ASP.NET MVC3 where I am unable to upload files larger than 4mb. I am currently using jquery.form.js for the file upload process and utilizing ajax to post the form to the server side. It works perfectly fine whe ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

Develop a custom directive that incorporates ng-model and features its own distinct scope

UPDATE - I have generated a Plunker I am in the process of developing a personalized directive to be utilized for all input fields. Each input will have distinct options based on the logged-in user's requirements (mandatory, concealed, etc), so I bel ...

An easy way to activate the save button automatically

Is there a way to automatically enable the save button when a user checks the checkbox and enters text in the input field? I'm not sure what steps are needed or if there is an alternative approach to achieve this. jQuery("input[type='text&apos ...

How to submit a textarea with the enter key without needing to refresh the page

I'm attempting to handle the submission of a textarea when the user hits the enter key, storing the text in a variable, then swapping out the form with the text and adding a new form at the end, all without refreshing. I had success doing this with an ...

Expand or collapse level 1 nodes with v-treeview component

I have created a special button in my tree view that has the ability to toggle open and close all nodes within it. The button code: <v-btn @click="toggleTreeview" /> Here is my v-tree markup: <v-treeview :value="x" @inpu ...

Is there a way to transfer table row data to another table by simply clicking on the corresponding checkbox in the same row?

I'm working with a table that includes 4 fields: service, amount, tax, and action. My challenge is to have the data from any row in the first table added to a second table when its checkbox is selected. The second table should have the same fields a ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

Adding JSON data to an array in Angular JS using the push method

I am encountering difficulties with adding data to an existing array. Currently, I have set up a table to display the data, but I want to also include the data in the table when a user enters an 8-digit barcode. Factory angular.module('app.pickU ...

Setting up a secure HTTPS server using Node.js and Express.js

Currently in the process of setting up a HTTPS server using Node.js and Express.js. This is what I have so far: const filesystem = require('fs'); const express = require('express'); const server = express(); const http = require(&apos ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

The Bootstrap modal fails to open

I am currently working on implementing a Navbar button that triggers a Bootstrap modal containing a form. While looking for resources, I stumbled upon a useful script at https://gist.github.com/havvg/3226804. I'm in the process of customizing it to su ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...