What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property.

  function reduceNodesRegistry(source: any) {
     if (!source.registry) return source;

    return {
      ...source,
      children:
        source.children &&
        source.children
          .map(reduceNodesRegistry)
          .filter((item: any) => item.registry),
    };
  }

  console.clear();
  console.log("##########");
  console.log(reduceNodesRegistry(source));

Full code with model by link

Wondering why nodes with registry: false are not being hidden?

Edition 1:

  reduceNodesRegistry(source: any) {
    if (typeof source.registry !== "undefined" && source.registry === false)
      return source;

    return {
      ...source,
      children:
        source.children &&
        source.children
          .map(this.reduceNodesRegistry.bind(this))
          .filter(
            (item: any) =>
              typeof item.registry === undefined || item.registry === true
          ),
    };
  }

Still not hiding nodes where registry: false.

Third attempt:

  reduceNodesRegistry(node: any) {
    return {
      ...node,
      children:
        node.children &&
        node.children
          .map(this.reduceNodesRegistry.bind(this))
          .filter(
            (node: any) => node.registry || node.registry === "undefined"
          ),
    };
  }

Answer №1

origin lacks a truthy database, so the updateDatabase function simply returns origin without exploring the entries property.

let origin = {
    "title": "",
    "entries": [...]
}

Answer №2

When comparing values with undefined, it is recommended to use one of the following methods:

typeof item.registry === "undefined"

or

node.registry == undefined

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

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

Error: The NgTable in AngularJS is not defined when reloading the page

I have successfully implemented Angularjs NgTable with pagination inside a tab provided by Angularjs Material in various parts of my project. However, I am facing an issue where I am unable to reload the tables in this particular case. I am unsure of what ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure: { "time_1": 20, "time_2": 10, "time_3": 40, "time_4": 30 } and expecting a result in this format: [ { "key1": "time_1" ...

What is the best way to restrict the creation of objects in a JavaScript list?

Experiencing a fun challenge with HTML coding! Take a look at my ordered list in HTML: <ol id="myList"> <li>Tea</li> <li>Milk</li> <li>Water</li> </ol> <button onclick="myFunction()">Try it</ ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

What is causing the malfunction in communication between my React app and Express server via fetch requests?

I am currently facing an issue while trying to connect my react js frontend (hosted on localhost for testing purposes, and also on my S3 bucket) to my node.js/express server deployed on an AWS Elastic Beanstalk environment. To resolve a CORS error, I recen ...

Field that only permits numerical input without triggering events for other characters

I've encountered some issues with the default behavior of the HTML number input and I'm looking to create a simple input that only allows numbers. To address this, I have developed a directive as shown below: import { Directive, ElementRef, Hos ...

Can you explain the distinction between the controls and get methods used with the FormGroup object?

I have encountered an interesting issue with 2 lines of code that essentially achieve the same outcome: this.data.affiliateLinkUrl = this.bookLinkForm.controls['affiliateLinkUrl'].value; this.data.affiliateLinkUrl = this.bookLinkForm.get(' ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...

Comparing Jquery's smoothscroll feature with dynamic height implementation

Recently I launched my own website and incorporated a smoothscroll script. While everything seems to be working smoothly, I encountered an issue when trying to adjust the height of the header upon clicking on a menu item. My dilemma is as follows: It appe ...

Updating the progress state of MUI linear determinate diligently

I currently have a modal set up that handles some asynchronous logic for submitting data to a database. The component I am using, called LinearDeterminate, is designed using Material-UI. You can find more information about it here: MUI Progress import { u ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

Fixing the error message "page attempting to load scripts from an unauthenticated source"

Can you help me troubleshoot an issue on my PHP page with ad scripts? I recently switched my site from HTTP to HTTPS and now the scripts are not appearing. Here is the error I found in the dev console: Failed to load resource: the server responded with ...

Preventing Event Propagation in Angular HTML

I am encountering an issue with stopPropagation, and I need assistance with implementing it in HTML and TypeScript for Angular. The problem is that the dialog opens but also triggers a propagation. Below is my code snippet in HTML: <label for="tab-two ...