Choose the root node in a JavaScript object

Given the following list:

table:any[] = [
    {
      name: 'A1 - John Doe', 
      icon: 'user-name',
      bold: true,
      code: 'NY',
      open: false,
      items: [
        {
          name: 'D3_AIR_ASBJHABSJAS',
          icon: 'package',
          open: false,
          items: [
            { 
              name: 'Charge Type 1',
              open: false,
              items: [
                { 
                  name: 'Charge Type 1.1',
                  icon: 'departure-nofill',
                  date: '12/10/2024'
                },
                { name: 'Charge Type 1.2'},
                { name: 'Charge Type 1.3'},
                { name: 'Charge Type 1.4',
                  items: [
                    { name: 'Charge Type 2.1'},
                    { name: 'Charge Type 2.2'},
                    { name: 'Charge Type 2.3'},
                  ]
                },
              ]
            },
            { 
              name: 'Charge Type 2',
              open: false,
              items: [
                { name: 'Charge Type 2.1'},
                { name: 'Charge Type 2.2'},
                { name: 'Charge Type 2.3',
                  items: [
                    { name: 'Charge Type 2.1.1'},
                  ]
                },
              ]
            },
            { 
              name: 'Charge Type 3',
              items: [
                { name: 'Charge Type 3.1'},
              ]
            },
          ]
        },
        {
          name: 'Hotel Beach Park',
          icon: 'departure-nofill',
          date: '12/10/2024'
        }

      ]
    },
    {name: '567', code: 'NYF',
      items: [
        { name: 'Charge Type 3.1'},
      ]
    },
  ];

How can we select the parent node of a child with value { name: 'Charge Type 1.2'},

I attempted to use hasChildNodes(), but it did not work as expected.

var item={ name: 'Charge Type 1.2'};
var parent=getParentElement(item)

The desired output is:

{ 
              name: 'Charge Type 1',
              open: false,
              items: [
                { 
                  name: 'Charge Type 1.1',
                  icon: 'departure-nofill',
                  date: '12/10/2024'
                },
                { name: 'Charge Type 1.2'},
                { name: 'Charge Type 1.3'},
                { name: 'Charge Type 1.4',
                  items: [
                    { name: 'Charge Type 2.1'},
                    { name: 'Charge Type 2.2'},
                    { name: 'Charge Type 2.3'},
                  ]
                },
              ]
            }

Answer №1

Searching for the specific element within a tree can be achieved through recursion.

Below is an illustration

function locateParentElement(child) {
  const childID = child.id

  function recursiveFind(elements, parent) {
    for (let element of elements) {
      if (element.id === childID) {
        return parent;
      }
      if (element.children) {
        const result = recursiveFind(element.children, element);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }

  return recursiveFind(treeStructure, null);
}

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

Custom Type and Sending an Array to a Function

I'm struggling with passing an Array from a user-defined Type to a Function: User-defined Type (in a standard Module): Public Type JPrinters Available() As String Default As String Function to generate a list of all available printers (in a ...

Creating a complete webpage using HTML

Is there a method to load an HTML file and execute the embedded javascript to create a complete HTML page programmatically similar to how browsers do? Edit 1 - I am working on an application where I need to extract data from an HTML page on a remote websi ...

Guidelines for incorporating role-based permissions in a React application

I am developing a MERN application that has various features catering to different roles. I need the ability to display specific data, navigation options, and divs based on the user's role while hiding these elements from others. It is important to no ...

localization within vue component

if (self.form.pickupTime == '') { self.formError.pickupTime = 'Please enter a pickup time that is ready for collection.'; status = false; return status; } else { self.formError.pickupTime = ''; } I am struggling ...

Guide on Sending a JSON Response from an ASP.NET MVC Controller

As a developer working in a controller, I encounter the need to transfer an entity object (Product) back to a view for JavaScript usage. The process involves passing a model object from the action method to the view. While the model object includes necess ...

Tips for effectively transferring data between components in Angular 2

One of the challenges I'm facing is with my header component. It has a function that toggles a class on click, and it works perfectly within the header component. However, I now want to extend this functionality to my nav component in order to add cla ...

A set comprising of fourteen elements in various combinations

Hey everyone, I have a bit of a challenge that I am hoping to get some help with. I have an array with fourteen items, each of which can be either 0 or 1. I am trying to figure out all the possible combinations of these digits. I've attempted using it ...

Is there a way to stop the page from scrolling once I reach the bottom of a specific div within it?

My webpage has multiple divs that share a similar structure: <div style="height:200px; overflow:auto;"> <div style="height:300px;"> <!--There is a lot of content here--> </div> </div> When the user hovers ove ...

What is the Proper Way to Add Inline Comments in JSX Code?

Currently, I am in the process of learning React and I have been experimenting with adding inline comments within JSX. However, when I try to use the regular JavaScript // comments, it leads to a syntax error. Let me share a snippet of my code below: const ...

Type Script is throwing an unidentified error being encountered

I am a beginner in Type Script and I'm attempting to convert a small piece of javascript code into typescript, but I keep encountering an error: typeError list[i] is undefined. Here is my original js code: function handleDragStart(e) { this.style.o ...

What is the best approach for establishing an asynchronous connection to a MongoDB database?

Managing a MongoDB database using JavaScript and Node.js with Mongoose, I needed to retrieve an array containing the names of all collections in the database. Taking this into consideration, I implemented the following code snippet. let connection = mongoo ...

Guide on incorporating a Bootstrap date time picker in an MVC view

Is there a live example available that demonstrates how to implement the latest Bootstrap date time picker in an MVC view? In my project, I have already included: - jQuery. - Bootstrap JS. - Bootstrap CSS. ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Tutorial on integrating jquery ui's '.droppable' feature with the jQuery '.on' method

I have a main div with three inner divs labeled 1, 2, and 3 as shown below: <div id="main"> <div style="height:30px; background-color:yellow;" class="bnr">Banner</div> <div style="height:30px; background-color:yellow;" class=" ...

Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method: methods:{ ContactUs(){ this.$http.post("/api/contact-us").then((res)=>{ ///do new stuff },(err)=>{ //do new stuff }) ...

Merge two input fields into one to send data to the backend

I have created two input fields, one for selecting a date and the other for entering a time. Before submitting the form to the backend, I need to combine these two inputs into one variable. For example, <input type="text" name="myDate"> and <input ...

Using `ngIf` with a condition causes the original object to be lost in the `let` binding

Imagine I am keeping track of the user currently logged in using this approach. If the user is null, it means they are not logged in. When logged in, they can either be anonymous (without a name) or have a name. interface User { name?: string; } current ...

dijit.Tree: Managing Expand/Collapse Events

My mobile application requires Lazy Loading, so I need to handle the expand event. I am utilizing dijit.Tree from the Dojo library. However, the official documentation does not mention any onCollapse/onExpand events. I attempted to use the onClick event ...

Is there a way to determine if a string has any extra spaces at

Is there a way to ensure my text has a trailing newline using just one regex expression instead of two? Currently, I achieve this by using two separate regex expressions: myString.match(/[^\S\r\n]\n/) || myString.match(/[^\S\r ...

Guide on showing string array values in an alert popup using JavaScript

I am struggling to display a string array in a JavaScript alert popup. The goal is to show the string index or Serial Number, followed by a space and then a line break before displaying the value of each string in the array. Unfortunately, my current code ...