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

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Navigating within a React application using React Router 2.6.0 by triggering a redirection within a click

Currently, I am experiencing an issue while utilizing react-router for constructing a login system with firebase and react. The desired functionality involves redirecting the user to the home page upon successful authentication of their username and passw ...

What is the best way to enhance the capabilities of a current tinyMCE button?

I am interested in enhancing the capabilities of the default buttons in tinyMCE by adding additional functionality. I'm curious to know how this can be achieved. For instance, If I would like the paste button not only to paste content, but also perf ...

THREE.js : Chart Your Course in the Digital Realm

When I have a moving object controlled by code such as: dx = [not important]; dy = [not important]; dz = [not important]; d = new THREE.Vector3(dx, dy, dz); mesh.postion.add(d); How can I ensure that my mesh is facing the direction it's moving in? I ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

ExpressJS route handler encounters an error due to undefined 'this' reference

teamList.js class teamListCtrl { constructor() { this.data = "example"; } fetch(response, request) { console.log("DISPLAY ! ", JSON.stringify(this)); } } module.exports = new teamListCtrl(); //singleton router.js var express = require( ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

Converting a 3D image array in NumPy to a 2D array

I am working with a 3D-numpy array representing a grayscale image. Here is an example of how it looks: [[[120,120,120],[67,67,67]]...] Since it is a gray image, having every R, G, and B value the same is redundant. I am looking to create a new 2D array t ...

Having trouble retrieving the value of a textarea within a jQuery UI dialog box

I attempted to place a textarea within a dialog box, with the intention of retrieving the value of that textarea when the "ok" button is clicked. However, I am encountering difficulties in retrieving the value. What could possibly be causing this issue? ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

Vanishing Submenus

I'm experiencing an issue with my navbar and its drop-down menus. When I hover over the submenu, it doesn't stay visible as expected. I've tried different approaches such as using jQuery, the + operator in CSS, and even creating a separate h ...

Is it feasible to choose the component generated by this element?

My current dilemma involves a component that renders a form, however, it also has its own form "catcher". var FormUpload = React.createClass({ submit : function(){ var formdata =new FormData(); ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Is there a way to assign a texture to only one side of a plane while having a color on the opposite side?

I'm currently experimenting with creating a plane in three.js where one side is a texture and the other side is a solid color. My initial attempt looked like this: var material = new THREE.MeshBasicMaterial({color: 0xff0000, side: THREE.FrontSide, ma ...

Could someone please provide clarification on this specific JavaScript syntax? I am unsure about the usage of `const {

Although I am not very familiar with javascript, I have come across this syntax and I would greatly appreciate it if someone could help me understand it! Regarding Node.js const { check, validationResult } = require('express-validator/check') ...

Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component. Here is the filter method I am trying to use: filterHotels:function(){ var thisHotels = this.hotelRoomArr; console.log(this.hotelRoomArr['107572']['rooms ...

Surprising outcome arising from simultaneous execution of numerous asynchronous operations on every individual object within an array

I'm fairly new to working with Node.js and I'm still trying to grasp the concept of callbacks and the asynchronous nature of Node.js. However, I've encountered a problem that I can't seem to solve. I've already searched extensively ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...