Retrieve the ancestors of a specific element within a deeply nested object

Storing data in a variable is very common, and this time we have it as follows:

let categories = [
    {
        name: "a",
        nodes: [
            {
                name: "aa",
                nodes: [
                    {
                        name: "aaa"
                    }
                ]
            },
            
            {
                name: "ab",
            },
            {
                name: "ac",
            },
            {
                name: "ad",
            }
        ]
    },
    {
        name: "b",
        nodes: [
            {
                name: "ba",
            },
            {
                name: "bb",
            },
            {
                name: "bc",
            },
            {
                name: "bd",
            }
        ]
    }
];

We also have a recursive function designed to work with the variables mentioned above - categories and name.

function getCategoryParents(categories, name) {
    for (let index = 0; index < categories.length; index++) {
        const category = categories[index];
        if (category.name === name) {
        }
        if (category.nodes && category.nodes.length) {
            category.nodes.forEach(cat => this.getCategoryParents([cat], name));
        }
    }
}

The goal here is to generate an array of names that includes the provided name along with its parent names.

For instance, calling

getCategoryParents(categories, "aaa")
should result in ["a", "aa", "aaa"]. This is because aa is the parent of aaa and a is the parent of aa.

I hope this explanation serves its purpose.

Answer №1

I made some modifications to your code in order for it to correctly return values when matching items are found:

function getParents(arr, name) {
  for (let child of arr) {
    if (child.name === name) {
      return name;
    } else if (child.nodes.length > 0) {
      var x = getParents(child.nodes, name);

      if (x) return Array.isArray(x) ? [child.name, ...x] : [child.name, x];
    }
  }
}

let categories = [
  {
    name: "a",
    nodes: [
      {
        name: "aa",
        nodes: [
          {
            name: "aaa"
          }
        ]
      },
      {
        name: "ab"
      },
      {
        name: "ac"
      },
      {
        name: "ad"
      }
    ]
  },
  {
    name: "b",
    nodes: [
      {
        name: "ba"
      },
      {
        name: "bb"
      },
      {
        name: "bc"
      },
      {
        name: "bd"
      }
    ]
  }
];

const result = getParents(categories, "aaa");
console.log(result); // ["a", "aa", "aaa"]

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

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Leveraging $http or $timeout in conjunction with $stateProvider in AngularJS

I am seeking guidance on loading a template for a specific state in Angular using $http after coming across this question on Stack Overflow: Is it possible to load a template via AJAX request for UI-Router in Angular? The documentation for ui.router demon ...

Passing an undefined value to the database via AJAX upon clicking a button

Hi there, I'm currently working on a table where I'm trying to perform an inline edit and update the value in the database by clicking on a button (an image). I've attempted to use an onclick function, but it seems to show "value=undefined&a ...

Challenges integrating Jquery with Flask

When attempting to add an HTML element using jQuery, I encountered an exception from Flask: jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static' The string seems correct, but I'm unsure about what the issue ...

Steps to obtain an array and utilize it in a datasource

Currently, I am facing a dilemma with an ajax call that retrieves an array: function test(){ $.ajax({ url: '/whatever/here'. data: data, }).done(function(newData){ var getArray = newData.SubData; newResult ...

View saved local storage information

I have an inquiry regarding saving data using localStorage for a shopping cart feature. I am able to list the data on one page through console.log but am facing difficulties in calling the data on another page. Can anyone assist with this? The Product page ...

Creating Irregular-shaped Array

As I work on a program to display a jagged array, I encountered some challenges. Initially, I tried using a foreach loop but it failed to print the array when the program was executed. Switching to a for loop resulted in a System.IndexOutOfRange exceptio ...

Use the fetch method to send a request from an HTML file that is being served through a

In my current setup, I have this code snippet to serve an HTML file via Go server. func main() { http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { path := r.URL.Path if path == "/" { pa ...

Is there a PHP function that functions similarly to JavaScript's "array.every()" method?

As I work on migrating JavaScript code to PHP, I am facing the challenge of finding a replacement for the array.every() function in PHP. I have come across the each() function in PHP, but it doesn't quite meet my requirements. ...

Creating a bar chart with JavaScript Canvas using for loops

I am currently struggling to change the color of individual bars in a bar chart. Right now, they are all green and I would like to customize each array with different colors. For example, I want the "Mon" bar to be red and the "Tues" bar to be blue. Below ...

jQuery - How come my string values are getting cut off?

It's been a while since I last worked with jQuery, and I seem to be missing something obvious that's affecting my calculations. I have various text boxes for Weight, Moisture %, and Number of Filled Squares, as well as a multi-select option for ...

Place form at the center of the Bootstrap Modal

My question is, how can I center the entire form, including the input fields and labels, within the modal? Here is also a helpful Fiddle: http://example.com, although the snippet provided should work as well. <script src="https://example.com/bootstr ...

Preparing JSON data for creating a wind map with Leaflet

I am currently working on converting netCDF data to JSON in order to use it with leaflet-velocity. This tool follows the same format as the output of grib2json used by cambecc in earth. An example of sample JSON data can be found at wind-global.json. By u ...

What causes differences in the resulting width between buttons and inputs as opposed to divs and anchor tags?

Check out this JS Bin: http://jsbin.com/ojiJEKa/1/edit I have a question regarding the different width results of <div> and <a> compared to <input> and <button>, even though they have the same style applied. Can anyone explain why ...

Generating and verifying checksums for strings in Node JS: A step-by-step guide

I am in the process of rewriting a function in Node.js for generating and verifying checksums for payment transactions. I am new to coding in Node.js and need some guidance. The code I have received from the Service Provider needs to be converted into Nod ...

Exploring the process of setting up reactive forms with AngularJS to handle arrays

I am working on setting up a reactive form for AngularJS and need to initialize certain fields: initializeBusinessEposForm(): void { this.businessEposForm = this.formBuilder.group({ custom_pos_priority: new FormControl(false), custom_float_ ...

The constant frustration of trying to extract a predefined AJAX return value, only to

My Ajax call and PHP function are causing an issue in Firefox. Despite receiving an HTTP 200 status, the response shows the value "false," but it is not being passed to the success part of the Ajax handler - instead, I always get undefined. I have plenty ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

Utilize JavaScript to assign a button with identical functionality as another button

After developing a slick slider, I decided to add custom arrows. The standard method from slick involves using prevArrow: and nextArrow:, but I wanted the buttons outside of the slick-slider container. To achieve this, I placed additional prev and next but ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...