Incorporate a new attribute into objects within a designated level of a tree structure in

I am working with an array of objects structured as a tree. I have a requirement to add a new property called "dateType" to the objects at the 3rd level.

let tree = [
    {
      id: 1,
      name: "parent1",
      children: [
        {
          id: 2,
          name: "child1",
          children: [
            { id: 4, name: "subChild1" },
            { id: 5, name: "subChild2" }
          ]
        },
        { id: 3, name: "child2" }
      ]
    }
  ];

The desired structure should look like this:

let tree = [
    {
      id: 1,
      name: "parent1",
      children: [
        {
          id: 2,
          name: "child1",
          children: [
            { id: 4, name: "subChild1", dateType: "test" },
            { id: 5, name: "subChild2", dateType: "test" }
          ]
        },
        { id: 3, name: "child2" }
      ]
    }
  ];

Is there a more efficient way to achieve this, as my current approach requires iterating multiple levels?

 custTree(res) {
      let result = [];
      res.forEach(level1 => {
        level1.children.forEach(level2 => {
          level2.children.forEach(level3 => {
console.log(level3)//nothing here
            //code here
          });
        });
      });
      return result;
    },

Note: The tree structure is dynamic and always three levels deep, but the update to the "dateType" property should be applied at the last level.

Answer №1

An efficient method involves employing both iteration and recursion to verify if the level is zero to facilitate an update with a new attribute.

This particular technique utilizes a zero-based level for modifying the objects within the data structure.

function update(array, level, object) {
    if (level) array.forEach(o => update(o.children || [], level - 1, object))
    else array.forEach(o => Object.assign(o, object));
}

let tree = [{ id: 1, name: "parent1", children: [{ id: 2, name: "child1", children: [{ id: 4, name: "subChild1" }, { id: 5, name: "subChild2" }] }, { id: 3, name: "child2" }] }];

update(tree, 2, { dateType: 'test' });

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

Answer №2

It seems like your goal is to add a property at the deepest level of your tree structure without knowing its height in advance. If your tree has a height of 5, then you aim to add the property to all nodes at that specific level.

One effective approach is to employ a breadth-first traversal method. This way, you can systematically navigate through each level, ultimately identifying the deepest level by recognizing when the subsequent level is empty.

To streamline this process, consider developing a utility function that returns an array containing the nodes of the deepest level. With this array in hand, you can easily manipulate the nodes according to your requirements:

function findDeepestLevel(tree) {
    let deepestNodes = [];
    let currentLevel = [];
    let nextLevel = tree;

    while (nextLevel.length) {
        deepestNodes = currentLevel;
        currentLevel = nextLevel;
        nextLevel = currentLevel.flatMap(node => node.children || []);
    }
    
    return deepestNodes;
}

// Sample tree structure
let tree = [{id: 1, name: "parent1", children: [{id: 2, name: "child1", children: [{id: 4, name: "subChild1"}, {id: 5, name: "subChild2"}]}, {id: 3, name: "child2"}]}];

let deepestLevelNodes = findDeepestLevel(tree);

// Modify the nodes as needed
for (node of deepestLevelNodes) {
    node.dataType = "example";
}

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

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...

Tips for displaying javascript code containing variables in the executeScript method

I'm currently working on a selenium script that involves executing JavaScript code using the executeScript method. I've run into an issue when it comes to handling single (') and double quotes (") while passing variables. Not Working: js.e ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Using Yii2, create a button with an onclick event that executes a JsExpression

I need to submit a form with an array of elements whose number is unknown. class DynamicForm extends Model { /** var string[] */ public elements[]; } In the view where the form submission takes place, I want to include a button that triggers a Ja ...

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

Dropzone.js: Creating a personalized file explorer to include files that have already been uploaded

Don't worry, this isn't your typical "can't load files from the server" query... I'm looking to allow users to view files on the server in a bootstrap modal and then select specific files. After selection, I want to close the modal and ...

Refresh needed for Material UI styles to load correctly in Next JS

UPDATE: Reproducible issue https://github.com/ganavol409/next-material-ui-classes-bug Issue seems to be related to Higher Order Components and importing useStyles from Material UI Implemented Solution: https://github.com/mui-org/material-ui/blob/master/ ...

Is there a method to retrieve a value from a node.js server when a div is clicked?

This is the EJS file I've created: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Sart Plug</title> <script src="http://code.jquer ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

Tips for accessing the value of a dynamically created textbox using JavaScript

Hello everyone, I have a couple of questions that I need help with. I am currently working on developing a social networking website similar to Facebook. On this platform, there are multiple posts fetched from a database. However, I am facing an issue w ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

What are some best practices for implementing responsive design using CSS @media queries with makeStyles in React.js Material UI?

const useStyles = makeStyles(theme => ({ wrapper: { width: "300px" }, text: { width: "100%" }, button: { width: "100%", marginTop: theme.spacing(1) }, select: { width: "100%", marginTop: theme.spacing(1) } })); I ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Using v-bind and AJAX in Vue.js

Transitioning from jQuery to Vue 2.0 has been a breeze for the most part, but I am facing challenges when it comes to handling AJAX calls and working with responses in Vue. One specific issue is related to a "Modal trigger" that opens a modal window upon ...

Experiencing difficulties loading Expo Vector Icons in Nextjs

I've spent countless hours trying various methods to accomplish this task, but unfortunately, I have had no luck so far. My goal is to utilize the Solito Nativebase Universal Typescript repository for this purpose: https://github.com/GeekyAnts/nativ ...

Learn the process of fetching checkbox values using JavaScript with this snippet

Is it possible to retrieve the name of the selected checkbox values/labels from the following code: <input id ="abc" value="abeexch" type ="checkbox"> <input id ="nam" value="suns" type ="checkbox"> If a checkbox is selected, how can I obtain ...

Sending JSON Data from Angular2 Component to Node.js Server

Currently, I am facing an issue where I am unable to successfully insert data into a database using Angular2 and Node.js. Upon running my script, I use console.log(this.address); to verify that I am passing json, and the output in the console is as follow ...