Incorporating parent ID data into hierarchical property structures

I am looking to extract the ID values from the previous object and construct an array of IDs within each parent item. The process must be generic and should not rely on the property names. However, all properties inherit a base class called SubResource. Only arrays that inherit from the SubResource class should be included in the identifierHierarchy.

export abstract class SubResource {
  public id: number;
  public identifierHierarchy: number[] = [];
}

Consider the following data snippet:

let data = [{
  "id": "1",
  "name": "Deer, spotted",
  "parents": [
    {
      "id": "133",
      "name": "Jaime Coldrick",
      "children": [
        {
          "id": "0723",
          "name": "Ardys Kurten",
          "grandchildren": [
            {
              "id": "384",
              "name": "Madelle Bauman"
            },
            {
              "id": "0576",
              "name": "Pincas Maas"
            },
            {
              "id": "5",
              "name": "Corrie Beacock"
            }
          ]
        }]
    }]
}]

The desired outcome is for the objects' values to be as follows:

[{
    "id": "1",
    "name": "Deer, spotted",
    "parents": [{
        "id": "133",
        "name": "Jaime Coldrick",
        "identifierHierarchy": ["1"],
        "children": [{
            "id": "0723",
            "name": "Ardys Kurten",
            "identifierHierarchy": ["1", "133"],
            "grandchildren": [{
                    "id": "384",
                    "name": "Madelle Bauman",
                    "identifierHierarchy": ["1", "133", "0723"]
                },
                {
                    "id": "0576",
                    "name": "Pincas Maas",
                    "identifierHierarchy": ["1", "133", "0723"]
                },
                {
                    "id": "5",
                    "name": "Corrie Beacock",
                    "identifierHierarchy": ["1", "133", "0723"]
                }
            ]
        }]
    }]
}]

Answer №1

I believe the following solution could be effective:

function createHierarchy(items: any[], path: string[], legacy: string[] = []) {
    items.forEach(item => {
        if (legacy.length)
            item.pathToAncestors = legacy;
        if (path.length)
            createHierarchy(item[path[0]], path.slice(1), [...legacy, item.id]);
    });
}

createHierarchy(data, ['parents', 'children', 'grandchildren']);

Answer №2

This solution may not be as strongly type-safe as I prefer, however...

export class RestHierarchyService {
  public static assignHierarchyIdentifiers(subResource: SubResource | any, parentIdentifiers: any): void {
    const composedSubResources = Object.entries(subResource)
      .filter(([key, value]) => key !== 'identifierHierarchy' && value.constructor === Array)
      .map(([key, value]) => Object.values(value).reduce(x => x));

    subResource.identifierHierarchy = parentIdentifiers;
    composedSubResources.forEach(x => RestHierarchyService.assignHierarchyIdentifiers(x, [...parentIdentifiers, subResource.id]));
  }
}
ancestry.forEach(x => x.parents.forEach(y => RestHierarchyService.assignHierarchyIdentifiers(y, [x.id])));

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 application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. https://i.sstatic.net/x3rRv.png s ...

Angular is unable to retrieve the /page resource

I attempted to deploy an angular application on Google Cloud, however, I encountered an issue where only the home page was properly deployed. Whenever I tried clicking on any other button in the navigation bar, it resulted in an error message stating "Erro ...

The data type '{ [key: string]: number; }' cannot be assigned to type 'T'

I’m working with a complex TypeScript type and trying to manage it within a function. Here’s what I have: type T = { a: number } | { b: number } function func(k: 'a' | 'b', v: number) { // error message below const t: T = { ...

Errors occurring during the building process in NextJS within the __webpack_require__ function

I am currently in the process of migrating a website from React-Fuse to NextJS with React. Everything is working smoothly except for an error that keeps popping up when I try to create a build: > Build error occurred TypeError: Cannot read property &apo ...

Setting default values for properties in Angular 2 components - A step-by-step guide

When creating Angular 2.0 components, how can default values be assigned to properties? For instance - I wish to initialize foo with 'bar', but it may get changed to 'baz' immediately through binding. How does this process unfold in th ...

a function that is not returning a boolean value, but rather returning

There seems to be a simple thing I'm missing here, but for the life of me, I can't figure out why the function below is returning undefined. var isOrphanEan = function isOrphanEan (ean) { Products.findOne({ 'ean': ean }, func ...

Number each element in sequence

Looking to give sequential numbering to elements by iterating through them. For instance, if there are 6 input elements, the goal is to update their names correspondingly like "name=input1", "name=input2", and so on. This involves using a for loop to reas ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Tips for generating a dynamic JavaScript object that contains a function as its value

I am in search of a dynamic method to generate Quasar Table column definitions. While the existing method shown below does work, I believe that replacing the lengthy switch statement with a for loop would be a more efficient solution. How can I implement ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Retrieve data from MongoDB using the $and query operator only when the condition of $and is satisfied within the same index of a document, particularly in the case of a doubly

1. Locating a Match: Strict Criteria within Array Elements Consider the following scenario with two documents stored in a mongoDB: {_id: 1, people: [{height: 10, age: 10}, {height: 5, age: 5}]} {_id: 2, people: [{height: 10, age: 5}, {height: 5, age: 10 ...

What steps can I take to troubleshoot this issue involving Django and AJAX?

Looking to pass the selected ID of an option via an AJAX request to Django 2.1, but encountering errors. As a newcomer to Django and web development, I would appreciate any help in resolving this issue. document.addEventListener('DOMContentLoaded&apos ...

Tips for concatenating elements to a previous state array when using an arrow function within the setState method?

When I drag and drop images to React-Dropzone library, I want to append them to the previous file state. const [files, setFiles] = useState([]) ... const { getRootProps, getInputProps, isFocused, isDragAccept, is ...

Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths: Firstly, to serve as a protection against unauthorized access by utilizing next-auth. Secondly, to redirect authorized users from specific pages. For example, if an authorized u ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Create a new Chart.js Chart by using the data retrieved from an AJAX request and encoded in JSON

I am currently working on drawing a chart using the chart.js library. The initial draw works perfectly fine, but I am facing issues when trying to redraw the doughnut chart with new data retrieved from an ajax call. My approach involves PHP and Codeignite ...

Converting a collection of div elements into a JavaScript array without using jQuery

Is there a way to transform a list of HTML divs into a JavaScript array? Below is the snippet of HTML code: <div class="colors"> <div>Red</div> <div>Blue</div> <div>Orange</div> <div>Green< ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Adding the elements within a multidimensional array

I'm dealing with a complex multi-dimensional array structure that looks like this: Array( [0] => Array( [data] => Array( [value] => 10, [beta] => 0.5 ), [name] => 'bob' ), [1] => Array( ...