Ways to decrease the size of this item while maintaining its child components?

Here is an object that I am working with:

{
  "name": "A",
  "children": [
    {
      "name": "B",
      "open": false,
      "registry": true,
      "children": [
        {
          "name": "C",
          "children": [
            {
              "name": "D",
              "children": []
            }
          ]
        },
        {
          "name": "E",
          "registry": true
        }
      ]
    }
  ]
}

I am trying to simplify this tree structure and extract only the nodes where registry is set to true.

First, I attempted to locate all these nodes:

public nodesRegistry = new Map();

findRegistryNodes(node: TreeNode) {
  if (!node) return;

  if (node?.registry) {
    this.nodesRegistry.set(node, node);
  }

  if (node.children)
    node.children.forEach((node: TreeNode) => {
      this.findRegistryNodes(node);
    });
}

Next, I need to reconstruct the tree:

const parents = this.getParentNodeRegistry();
const children = this.getChildrenNodeRegistry(parents);

This method identifies all parent nodes for the discovered children:

getParentNodeRegistry() {
  const nodesWithRegistry = new Map<string, TreeNode>();

  for (const node of this.nodesRegistry.keys()) {
    let parent = node.parent;

    do {
      if (parent.parent && !parent.parent.parent) {
          nodesWithRegistry.set(parent.name, parent);
          break;
      }

      parent = parent.parent;
    } while (parent);
  }

  return nodesWithRegistry;
}

Then, we collect all children nodes:

getChildrenNodeRegistry(nodes: Map<string, TreeNode>) {
    return Array.from(nodes.values()).reduce((children, node) => {
        this.reduceNodesWithRegistrer(node);
        return (children = children.concat(node));
    }, []);
}

The resulting nodes still contain elements without the registry: true property. How can this be resolved?

Answer №1

I believe this code snippet fulfills your requirements:

const data = {
  name: "Apple",
  children: [
    {
      name: "Banana",
      open: false,
      registry: true,
      children: [
        {
          name: "Cherry",
          children: [
            {
              name: "Date",
              children: []
            }
          ]
        },
        {
          name: "Elderberry",
          registry: true
        }
      ]
    }
  ]
};

function filterRegistryTrue(data) {
  let { children, ...rest } = data;
  const newData = { ...rest };

  if (children) {
    children = children.filter(({ registry }) => !!registry);
    newData['children'] = children.map((child) => filterRegistryTrue(child));
  }

  return newData;
}

console.log(filterRegistryTrue(data));

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 correct syntax for utilizing a variable in inline styles within ReactJS, specifically when working with the --i:0

            The question has been raised previously, but unfortunately, it was left unanswered in this thread. The variables play a crucial role in this piece of code as they are intended to be utilized in various CSS functions for animating them wi ...

Invoking functions from controllers to mongoose schema module in Node.js

Greetings everyone, I am fairly new to working with Node.js so let me share my current dilemma. I have set up a mongoose schema for handling comments in the following structure: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const ...

What is the best way to generate a JSON object with Angular and showcase its content through HTML?

Currently, I am dealing with a JSON object that is completely unfamiliar to me. Without knowing the keys or values of this object, I was able to successfully manipulate it and extract the necessary information. Ultimately, I have generated an array (whic ...

A guide to eliminating TextRow and inserting a string into JSON using NodeJs

To remove TextRow and add the string true to JSON in NodeJs, I have included the following code: NodeJs Code: function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { let key = obj[property] if (!acc[key]) { ...

Typescript void negation: requiring functions to not return void

How can I ensure a function always returns a value in TypeScript? Due to the fact that void is a subtype of any, I haven't been able to find any generics that successfully exclude void from any. My current workaround looks like this: type NotVoid ...

Exploring methods to successfully upload a blob to Firebase and modify it using cloud functions

For days now, I've been attempting to successfully upload a file to firestorage using firebase functions but haven't had any luck. This is the progress I've made so far: export const tester = functions.https.onRequest(async (request, respons ...

Regular expressions are effective tools, but they may not be as functional within an

Trying to validate URLs using a regex has been tricky. The regex I have works perfectly fine on regex101.com, but for some reason it keeps failing validation when implemented in my Angular field. I'm at a loss as to how to tweak it so that Angular wil ...

Maintaining selected options in select lists while updating model data in Angular

New to Angular and exploring the Product object with Sku objects nested inside. An app allows users to fetch a product, resulting in the Product object being assigned to $scope.product: var app = angular.module('app', []); app.controller(&apos ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

Create a visual layout showcasing a unique combination of images and text using div elements in

I created a div table with 3 images and text for each row, but I'm struggling to make all the text-containing divs uniform in size. How can I achieve this? Also, I need to center this table on the screen, and currently using padding to do so. Is there ...

What is the best way to remove empty elements from an Array?

Having an issue with my API post request. If no values are entered in the pricing form fields, I want to send an empty array. I attempted to use the filter method to achieve this but it still sends an array with an empty object (i.e. [{}]) when making the ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Error: Invalid parameter detected for Shopify script-tag

I'm encountering a persistent error message stating { errors: { script_tag: 'Required parameter missing or invalid' } } This issue arises when attempting to upload a script tag to a storefront. Currently, I'm just experimenting with s ...

Is it possible to reference a .js file within an HTML file using AngularJS?

Having a slight issue with an email function. I experimented with the 'nodemailer' package and successfully sent an email when coding in a .js file. Upon calling the .js file (node emailfile.js), the email was received as expected (code provided ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

Launch a new Windows form upon clicking an HTML button using DotNetBrowser

I attempted to open a Windows form using the DotNetBrowser control with specific HTML content as shown in the code below. Upon clicking a button on the HTML page, I want to hide the loaded form and then display the second Windows form. Here is the C# cod ...

Issue with table display within <div> element in React

Recently diving into React, I find myself in a situation where I need to display data in a table once it's ready or show 'Loading' if not. Currently, my render() function looks like this: return ( <div> { this.state.loaded ...

Click on the div to add items from an array into it

I have a unique set of lines stored in an array: var linesArr = ["abc", "def", "ghi"]; In my JavaScript, I dynamically create and style a div element using CSS: var div = document.createElement("div"); div.className = "storyArea"; div.in ...