Javascript recursive method for fetching data entries

Seeking a solution to retrieve interconnected records based on a parent column, where the relation can be one or many on both ends.

After attempting a recursive function without success, I found my code became overly complex and ineffective. Is there a standard method to approach this issue?

Here is a sample dataset:

id       parent_id

Record1    main
RecordA1   Record1
RecordA2   Record1
RecordB1   RecordA1
RecordC1   RecordB1

This was my initial attempt at the code:

data.first_parent_id = main_parent_id;
data.categories = [];

function getCategories(parent_id) {
  // -> fetch data with columns matching parent_id from input parameter
  data.categories.push({
    id: id,
    parent_id: gr.getValue('parent_id')
  });

  return data.categories;
}

getCategories(data.first_parent_id);

The desired output is an object array structured like this:

  obj = {
    id: record1,
    children: [
      {
        id: RecordA1,
        children: [
          id: RecordB1,
          children: [
            id: RecordC1,
            children: [

            ]
          ]
        ]

      },
      {
        id: RecordA2,
        children: []
      },
      {
        id: value,
        children: []
      }
    ]
  };

Any advice or suggestions are greatly appreciated.

Thank you!

Answer №1

Given the structure of the variable categories as shown below:

This method involves utilizing the reduce function in conjunction with a recursive approach to identify parent categories.

//  id          parent_id
var categories = [
  ['Record1'],
  ['RecordA1', 'Record1'],
  ['RecordA2', 'Record1'],
  ['RecordB1', 'RecordA1'],
  ['RecordC1', 'RecordB1']
];

//  id          parent_id
var categories = [
  ['Record1'],
  ['RecordA1', 'Record1'],
  ['RecordA2', 'Record1'],
  ['RecordB1', 'RecordA1'],
  ['RecordC1', 'RecordB1']
];

var result = categories.reduce(function (acc, cat) {
  var id = cat[0], parent = cat[1];

  function findParent(obj) {
    if (obj.id === parent) return obj;
    else {
      if (obj.children) {
        for (var c of obj.children) {
          var f = findParent(c);
          if (f) return f;
        }
      }
    }
  }
  
  function getObject() {
    return { id: id, children: [] };
  }

  if (parent) {
    var found = findParent(acc);
    if (found) {
      found.children.push(getObject());
    } else {
      acc = Object.assign(acc, getObject());
    }
  } else {
    acc = getObject();
  };

  return acc;
}, {});

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

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

The JSON file is populated with just a single object when using a for loop

I am attempting to loop through a JSON file and extract specific key values to create a new JSON file: def get_rubrik_failed_archives_main(): with open("get_failed_archives.json") as json_file: json_data = json.load(json_file) for ...

Router Express, parsing the body, and submitting a POST request

I have been experimenting with express.Router to organize my routes and testing post requests using Postman. I noticed that when I make a post request to /test without using router body-parser, everything works fine and I can view the body content. However ...

Struggling with adding two-digit numbers in a JavaScript calculator

While I can add single digits with no problem, adding double digits proves to be a bit tricky. The split method in this if statement is useful for isolating individual numbers, but it struggles when dealing with double digit numbers. if(e.value == '= ...

What is the best way to replace null with None in a Python project when making a post request?

During my work in Python, I encountered the following scenario: v = None Additionally, there was a post request like this: issue = { "fields": { "project": ...

Accessing data in a JSON file can be done by

Similar Question: Reading a Json Array in android I am attempting to extract the field names from a string using JSON. While I have successfully retrieved the values, I am struggling to retrieve the field names. Here is an example: String strjson: { ...

Retrieve the value of an input text within a table data cell using JavaScript

I have set up a table using CGridView, which includes input text fields for user input. The problem I'm facing is that I can retrieve the text from table cells without input fields, but not from those containing input fields. PHP: <?php $this-> ...

Tips for optimizing the "framerate" (setInterval delay) in a JavaScript animation loop

When creating a JavaScript animation, it's common practice to use setInterval (or multiple setTimeouts) to create a loop. But what is the optimal delay to set in these setInterval/setTimeout calls? In the jQuery API page for the .animate() function, ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Improving the display of events with fullcalendar using ajax requests

I have integrated the fullcalendar plugin from GitHub into my project. I am looking to implement a feature where I can retrieve more events from multiple server-side URLs through Ajax requests. Currently, the initial event retrieval is functioning proper ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

Display geographic data using d3 with geoJSON

I am struggling to render a geoJSON file using d3 because I am having trouble targeting the correct features for projection. Instead of working with the typical us.json file used in many d3 examples, my current map focuses on United States "Commuting Zone ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

How can we optimize ternary statements within ternary statements in Type Script and React Native for best practices?

Can you help me optimize this code snippet that uses nested ternary operators for better readability and correctness? <TouchableOpacity style={ darkMode ? filterState === 'A' ? styles.activeButtonDark : styles.buttonDa ...

How to selectively disable buttons in a group using React

I am working with an array of data const projectTypeValues = [ { name: 'Hour', value: 'hour'}, { name: 'Day', value: 'day'}, { name: 'Session', value: 'session'}, { name: 'project', valu ...

:JSON encountered a problem interpreting the response from the Web Service

One of my web service methods looks like this: [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = FetchSitePerformanceAuto/{fromDate}/{country})] public Li ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

Deciphering JSON data outcomes in VB.NET

How can I extract specific data from the given code snippet stored in a textbox? { "items": [ { "snippet": { "channelId": "UCcTbyoZjhqoCn4yVawpMFDA", "title": "Forever - Stratovarius", "categoryId": ...

Difficulty with deploying Next.js to Vercel due to restrictions on rate limits when utilizing getStaticProps()

In my Next.js project connected to Apollo, I have around 50 static URLs fetching data using getStaticProps(). The performance is great, and I enjoy how the pages load. However, a problem arises when Vercel builds the static versions of these pages during d ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

What is the process for validating observations with an observer confirmation?

Can you explain what the of() function creates in this scenario and how it operates? public onRemoving(tag): Observable<any> { const confirm = window.confirm('Do you really want to remove this tag?'); return Observable.of(tag).fil ...