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

How can I populate a dropdown list in JavaScript with JSON data from a file?

I am experiencing difficulties when it comes to parsing JSON files for use in a dropdown list. JSON: { "BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina" } The goal is to populate the dropdownlist ...

Retrieve the data object in VueJS

(Regarding a currency conversion tool) In order to accurately convert currencies, I am looking to access an object structured like this: rates: AUD: 1.708562 SGD: 1.546211 When retrieving these rates from an API, they are not always in the desired o ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

How can I trigger a PHP function by clicking a button on a PHP page that has already been loaded?

While I've come across a variety of examples, I haven't been able to make them work for the simple task I need to accomplish. The code in these examples seems overly complex compared to what I require. In essence, I have a form that processes dat ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Is there a way for me to adjust the font size across the entire page?

Most CSS classes come with a fixed font-size value already set. For instance: font-size: 16px font-size: 14px etc. Is there a way to increase the font size of the entire page by 110%? For example, font-size: 16px -> 17.6 font-size: 14px -> 15.4 ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

Achieving the functionality of keeping the search query box and alphabetical search options visible on the page even after performing a search and displaying the results can be done by

I have set up a PHP page with search query field and alphabetical search options. When submitting the query, the results are displayed on the same page; however, I would like the results to show in the same location as the alphabetical search. Currently, ...

When checking if el.text() is equal to "string", it will return false, regardless of the actual content of the element being "string"

Looking at the code snippet below, it seems that the else block is always being executed instead of the if block. The alert confirms that the variable state has the value 'payment' as expected. var state = $('.check-state').text(); ale ...

Ensuring security against cross site scripting attacks on window.location.href

Currently, I'm utilizing window.location.href to redirect the page to an external URL: <Route exact path={rootUrl} component={() => { window.location.href =`https://${window.location.hostname}/www/testurl?google=true`; return null; }} /> How ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

Eliminating unnecessary whitespace between the bottom of the document and an element

I have a HTML page that when scrolled should limit scroll to the document height. It must not exceed the bottom of an element. Here is a screenshot for better understanding: https://i.stack.imgur.com/RaVg8.jpg The scrolling should be limited after the En ...

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

Accessing form data using Vue on submit

I'm working on a project that involves creating a form with a single input field and saving the data to a database. The technology I am using is Vue.js. Here is the template I have designed: <form class="form-horizontal" @submit.prevent="submitBi ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...