Sorting and saving and identifying the parent-child connections among elements within an array

I am currently developing an Angular application and here is the structure of my data:

data= [
    {
        "id": 2,
        "name": "Jamie",
        "objectId": 200,
        "parentId": null,
        "children": [
            {
                "id": 98,
                "name": "Rose",
                "objectId": 100,
                "parentId": 200,
                "children": [
                    {
                        "id": 1212,
                        "name": "Julie",
                        "objectId": 500,
                        "parentId": 100,
                        "children": []
                    }
                ]
            },
            {
                "id": 67,
                "name": "Kosy",
                "objectId": 700,
                "parentId": 200,
                "children": []
            }
        ]
    }
]

In my method, I will be receiving an input ID and name. For example, if the ID is 1212 and the name is "Julie", I need to traverse to the node where the ID is 1212 and the name is "Julie". Once this condition is met, I have to check whether the parent ID in children matches the object ID in the parent until the parent ID becomes null.

If the parent ID becomes null, it is considered as the last node, and the desired output should be an array in the following format. For ID 1212 and the name "Julie", the resultArray would be

resultArray = ["Jamie/Rose/Julie"]
, with data separated by slashes from parent to children.

Another example would be if I receive the ID as 67 and the name as "Kosy", then the result array would be

resultArray = ["Jamie/Kosy"]

Since the parent ID of Kosy is 200 and the object ID of Jamie is also 200, it indicates that Jamie is the parent of Kosy, resulting in the formatted data as mentioned above. I aim to create a dynamic code to handle large amounts of data at runtime while maintaining the same structure and logic.

How can I achieve this?

Answer №1

This problem was tackled by me with the code provided below. The challenge presented here is a classic tree-search scenario where special attention is required when checking parent nodes, which was easily addressed in this solution.

const data = [
    {
        "id": 2,
        "name": "Jamie",
        "objectId": 200,
        "parentId": null,
        "children": [
            {
                "id": 98,
                "name": "Rose",
                "objectId": 100,
                "parentId": 200,
                "children": [
                    {
                        "id": 1212,
                        "name": "julie",
                        "objectId": 500,
                        "parentId": 100,
                        "children": []
                    }
                 ]
             },
             {
                 "id": 67,
                 "name": "Kosy",
                 "objectId": 700,
                 "parentId": 200,
                 "children": []
              }
          ]
      }
];

// Function to search for the target within a node (not an array)
// To return true, must pass id comparison from the final node to this node as well
const findInNode = (node, id, name, output) => {
    if (node.name === name && node.id === id) {
        return true;
    } else {
        const children = node.children;
        if (!children) return false;
        // Find in children
        for (let child of children) {
            output.paths.push(child.name);
            if (findInNode(child, id, name, output)) {
                return child.parentId === node.objectId;
            }
            output.paths.pop();
        }
    }
}

// Function to search for the target in an array, used at the top-most level
const findInArray = (nodes, id, name, output) => {
    for (let node of nodes) {
        output.paths.push(node.name);
        if (findInNode(node, id, name, output)) {
            if (!node.parentId) {
                output.found = true;
                break;
            }
        }
        output.paths.pop();
    }
}

output = { paths: [], found: false };
findInArray(data, 1212, 'julie', output);

console.log(output.found);
console.log(output.paths.join('/'));

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

Print out the value of the element in the array using the console

Hey there! I have this array that I retrieved from MongoDB and I'm trying to figure out how to console log the value of item. Any tips or suggestions would be greatly appreciated! { "_id" : "61462a7bf3c0be993bcfdc3e", "item&qu ...

Issues with the sliding mechanism

When the condition is that the slider should be fixed and switched by pressing a button, each component works fine individually but breaks when used together. The issue arises when the first slide appears and the buttons work, but once the animation tran ...

Bits of code and the internet

When it comes to displaying code on the web, there are a few key steps involved: Encoding HTML entities Formatting The most basic workflow would involve: Start with a code snippet like: <html> I'm a full page html snippet <html>. ...

The webpage declined to show the content from 'https://www.youtube.com/watch?v=oKZRsBjQJOs' within a frame due to the 'X-Frame-Options' being set to 'sameorigin'

I'm struggling to incorporate a YouTube video into my website using a dynamic URL. I attempted to create a pipe for this purpose, but unfortunately it is not functioning properly. Here's the HTML code snippet from my file: <iframe width="6 ...

Executing jQuery code when reaching a specific moment in an HTML video

I wanted to modify the video playback so that it would loop a specific portion of the video continuously while still allowing the full video to be played. For example, if the video is 30 seconds long and I want to play 5-second segment starting at 10 seco ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

What is the reason behind V8's perplexing error notification?

When running this code on Chrome or Node (v8), an error message is displayed: Uncaught TypeError: f is not iterable function f(){} f(...undefined); Why is such an ambiguous error message generated in this case? Does it really have nothing to do with ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Is it possible to generate a basic HTML page using Express JS without utilizing Ejs or any other templating engine

I have a basic HTML file with a Bootstrap form, along with a simple API coded within. In my server.js file, I've specified that when I request /about, it should redirect me to the about.html page. However, instead of redirecting, I'm encountering ...

Navigate to a specific line in Vscode once a new document is opened

Currently, I am working on a project to create a VS Code extension that will allow me to navigate to a specific file:num. However, I have encountered a roadblock when it comes to moving the cursor to a particular line after opening the file. I could use so ...

Choose all immediate parent items on the list in the mmenu

Currently, I am working on a project and looking to incorporate the jQuery plugin mmenu (). Despite making some customizations to suit my requirements, I am facing a dilemma. In mmenu, clicking on a list entry navigates to the specified href and marks the ...

Clearing Out a Shopping Cart in Angular

Hey there, I have a little dilemma with my shopping cart system. I can easily add and delete products using an API. However, when it comes to deleting an item from the cart, I have to do it one by one by clicking on a button for each item, which is not ver ...

I am unable to retrieve the images stored in the array

I am facing an issue with extracting images from Firebase and saving them. The problem arises when the function completes without success. export const saveImages = async (images) => { let imgs = []; try { images.forEach(image => { ...

What is the best way to ensure that a mongoose .exec() callback has completed before checking the response object in express?

I am currently developing an application that utilizes Express, Mongoose, and Jest for testing. In order to test my application, I have set up a mongodb in local memory for testing purposes. However, I am facing an issue in some of my tests where the callb ...

Finding the substring enclosed by two symbols using Javascript

I'm working with a string that contains specific symbols and I need to extract the text between them. Here is an example: http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_se ...

Having issues with Vue 3 Typescript integration in template section

This particular project has been developed using the create-vue tool and comes with built-in support for Typescript. Key versions include Vue: 3.3.4, Typescript: 5.0.4 Here is a snippet of the code to provide context: // ComponentA.vue <script setup l ...

What could possibly be causing my app to exhaust CPU resources on Mozilla Firefox?

I have created a unique game application for Facebook. Currently, the app is not optimized with AJAX technology, resulting in multiple server requests causing high CPU usage (specifically in Firefox) which slows down the overall performance of the app. Alt ...

The spheres produced by the threeBSP method exhibit a lack of smoothness

Is there a way to smooth out the sphere when I reach the segment limit of 45? Despite trying to change the number of segments, if I hit the cap of 45, cutting it becomes difficult and other methods seem unavailable for creating a smoother sphere. var re ...

Why is it that when I store a DOM element reference in a JavaScript Array, I cannot reuse that stored reference to add an event listener

I have a little confusion and I hope someone can help me out. I am facing an issue with dynamically created buttons, where each button has a unique id. To keep track of these buttons in a well-organized manner, I store their references using a simple two-d ...

An adhesive feature that halts upon reaching a specific element

Can anyone help me create a fixed element that behaves like a sticky element when scrolling and reaches the top of another specified element? I want this fixed element to stay within the boundaries of the element I set as the "ground", preventing it from p ...