Updating the MLM binary tree system

In my JavaScript nested object, the IDs of objects increase in depth. By using JavaScript support, I added an object inside ID - 2 with a children array of 3. What I need is to update (increment) the IDs of all siblings in the tree. This code snippet should work for every case, for example, changing ID: 4 to 5 and updating its children IDs to 6, 7, 8, etc. Additionally, we need to adjust the parent ID as the ID changes.

(
[id] => 1
[parent_id] => 
[children] => Array
    (
        [0] => Array
            (
                [id] => 2
                [parent_id] => 1
                [children] => Array
                    (
                        [0] => Array
                            (
                                [id] => 3
                                [parent_id] => 2
                                [children] => Array
                                    (
                                    )

                            )

                    )

            )

        [1] => Array
            (
                [id] => 4
                [parent_id] => 1
                [children] => Array
                    (
                        [0] => Array
                            (
                                [id] => 5
                                [parent_id] => 3
                                [children] => Array
                                    (
                                    )

                            )

                        [1] => Array
                            (
                                [id] => 6
                                [parent_id] => 3
                                [children] => Array
                                    (
                                    )

                            )

                        [2] => Array
                            (
                                [id] => 7
                                [parent_id] => 4
                                [children] => Array
                                    (
                                    )

                            )

                    )

            )

        [2] => Array
            (
                [id] => 8
                [parent_id] => 1
                [children] => Array
                    (
                    )

            )

    )

)

Answer №1

This function is designed to update the IDs and parent IDs of nodes within a tree structure, incrementing them accordingly. It recursively traverses through the tree's children to update their IDs as well.

const updateIds = (tree) => {
  tree.id++;
  if (Number.isInteger(tree.parentId)) {
    tree.parentId++;
  }
  tree.children.forEach(child => {
    updateIds(child);
  })
}

Here is an enhanced version of the id-incrementing function:

const updateIds = (tree, insertedId) => {
  if (tree.id > insertedId) {
     tree.id++;
  }
  if (Number.isInteger(tree.parentId) && tree.parentId > insertedId) {
    tree.parentId++;
  }
  tree.children.forEach(child => {
    updateIds(child, insertedId);
  })
}

Answer №2

Here is a function I wrote:

let uniqueId = '';
function updateIds(tree, itemName, newTeam) {
    if (tree.name === itemName) {
        const childrenLength = tree.children.length;
        newTeam.id = tree.id + childrenLength + 1;
        uniqueId = tree.id + childrenLength + 1;
        tree.children = [...tree.children, newTeam];
    }
    if (uniqueId !== '' && tree.id >= uniqueId && tree.name !== newTeam.name) {
        tree.id++;
    }
    if (uniqueId !== '' && Number.isInteger(tree.parent_id) && tree.parent_id >= uniqueId && tree.name !== newTeam.name) {
        tree.parent_id++;
    }
    tree.children.forEach(child => { 
        updateIds(child, itemName, newTeam);
    });
    return tree;
}

}

Everything seems to be working perfectly except for one case where adding a sibling element at the root does not update the id of this sibling element.

Answer №3

If someone is seeking a solution for a similar problem that worked for me, here is the solution I found for adding an item:

function findLastChild(element) {
  let children = '';
  if (element.children.length > 0) {
    children = element.children[element.children.length - 1];
    return findLastChild(children);
  }
  return element;
}

function addNestedItem(array, itemName, newTeam) {
  array.forEach((element) => {
    if (element.name === itemName) {
      const lastItem = findLastChild(element);
      newTeam.id = lastItem.id + 1;
      element.children = [...element.children, newTeam];
    } else {
      return addNestedItem(element.children, itemName, newTeam);
    }
  });
  return array;
}

function updateNestedItemIndex(array, newTeam) {
  array.forEach((element) => {
    if (element.id >= newTeam.id && element.name !== newTeam.name) {
      element.id++;
    }
    return updateNestedItemIndex(element.children, newTeam);
  });
  return array;
}

const tempTree = addNestedItem([tree], team.name, newTeam);
const newTree = updateNestedItemIndex(tempTree, newTeam);

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

Modify the database value linked to an <input> element each time its value is modified

I attempted to create something similar to the example provided here $(document).ready(function(){ $('input[type=text]').keyup(function(){ var c=0; var a=$(this).attr('name'); //a is string //if var a change.. ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

How to Link an Object's Value to a Checkbox in Vue

My goal is to populate the array selectedParks with the value of each item. However, I am facing an issue where the value is always set to the string "item" instead of the actual value of the Park Object. Here is the code snippet: <ul class="list- ...

Interacting between Angular controllers and directives while maintaining separation of concerns

In my AngularJS project, I've implemented a directive within a module named ThreeViewer that displays WebGL scenes based on the specified source file. The code snippet below outlines the basic functionality: angular.module('ThreeViewer', [] ...

Exploring the capabilities of AngularJS directives through ng-html2js testing

Many questions have been raised about the ng-html2js plugin, but unfortunately, none of the answers provided were able to solve my specific issue. I meticulously followed the official installation guide and also referenced the example available at https:/ ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Transitioning from utilizing Jquery for post requests to implementing modern Promises

Currently, I am involved in a web application project that utilizes Flask and Python on the back-end with JavaScript on the front-end. I have been contemplating leveraging more modern styles like ES6/7 features such as Promises. In my development process, ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

Styling triangles within a CSS triangle

I'm attempting to design a webpage with a fixed triangle navigation element. The issue I am encountering is that I am unable to position smaller triangles inside the larger one, as shown in the image below. https://i.stack.imgur.com/1bTj8.png As th ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

Change the background color of a MUI ToggleButton based on a dynamic selection

const StyledToggleButton = styled(MuiToggleButton)(({ selectedColor }) => ({ "&.Mui-selected, &.Mui-selected:hover": { backgroundColor: selectedColor, } })); const FilterTeam = (props) => { const [view, setView] = ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

When the page is refreshed, the ContextProvider fails to mount

For the complete code, you can view it on codesandbox. Within my countries API application, I have implemented two Route components - <> <Header/> <Router> <Switch> <CountriesDataProvider> ...

Tips for performing matrix manipulation in Matlab:

I have two matrices in Matlab: matrix A of size m x n and matrix b of size 1 x n. Matrix b is structured such that it contains sequences of increasing values up to a certain number k (e.g. b = [1 1 1 2 2 3], n = 6). My goal is to iterate through each row ...

extracting values from an array using the map function in React

In React JSX, I have an array called levels that may contain arrays with various level names such as one, two, and three. Within my render function, I utilize {renderLevels} to display all levels separated by commas. This approach works well: const rende ...

Tips on transmitting JSON data from a Spring controller to JavaScript

Does anyone have experience with sending a JSON object from a spring controller to JavaScript and receiving it using AJAX? I would appreciate any guidance on how to accomplish this. ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

How can I use React to switch the visibility of a nested component from the parent container component?

Objective I am in the process of replicating a List Control Component using React and Redux, following the guidelines outlined in Google Material Design layout. This list control will enable users to create, rename, and delete items within the list witho ...