Filtering a nested array based on the value of an element's field in

I am trying to filter a nested array based on the value of an element field. The array that needs to be filtered is shown below. I want to filter by the checked value of each element. If the value is true, I want to keep the element; if false, discard it.

let rawData =[
      {
        name: 'red',
        checked: true,
        children: [
          {
            name: 'red1',
            checked: false,
            children: [
              {
                name: 'red11',
                checked: true,
                children: [
                  {
                    name: 'red111',
                    checked: false,
                    children: [
                      {
                        name: 'red1111',
                        checked: true,
                        children: []
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        name: 'blue',
        checked: false,
        children: [
          {
            name: 'blue1',
            checked: true,
            children: [
              {
                name: 'blue11',
                checked: true,
                children: []
              },
               {
                name: 'blue12',
                checked: false,
                children: []
              },
            ]
          }
        ]
      },
      {
       name: 'yellow',
       checked: false,
       children: []
      }
    ]

This is the desired result: (Filter every element and return it with checked equal true. If not equal true, just discard).

 let result =[
      {
        name: 'red',
        checked: true,
        children: [
          {
            name: 'red11',
            checked: true,
            children: [
              {
                name: 'red1111',
                checked: true,
                children: []
              }
            ]
          }
        ]   
      },
        {
          name: 'blue1',
          checked: true,
          children: [
            {
              name: 'blue11',
              checked: true,
              children: []
            }
          ]
        }
      ]

Below is my attempted solution (which does not work).

let result = rawData.filter(node => {
  function getCheckedData (node) {
    if (node.checked === true) {
      return node
    }
    if (node.children.length) {
      node.children.filter(c => {
        getCheckedData(c)
      })
    }
   return getCheckedData(node)
})

The node.children.filter never executes if the first level data has checked equal to true. What should I do to ensure that the children recursion continues regardless of the parent's checked status? Thank you!

Answer №1

One thing to note is that the code snippet doesn't handle the case where checked: 'false', is used, even though it represents a truthy value due to the word false being enclosed in quotes. So, let's just assume it means literal false.

let data =[
      {
        name: 'red',
        checked: true,
        children: [
          {
            name: 'red1',
            //checked: 'false', // ¯\_(ツ)_/¯
            checked: false,
            children: [
              {
                name: 'red11',
                checked: true,
                children: [
                  {
                    name: 'red111',
                    checked: false,
                    children: [
                      {
                        name: 'red1111',
                        checked: true,
                        children: []
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        name: 'blue',
        checked: false,
        children: [
          {
            name: 'blue1',
            checked: true,
            children: [
              {
                name: 'blue11',
                checked: true,
                children: []
              },
               {
                name: 'blue12',
                checked: false,
                children: []
              },
            ]
          }
        ]
      },
      {
       name: 'yellow',
       checked: false,
       children: []
      }
    ];

function checkItems(array) {
  return array.flatMap(
    item => item.checked
    ? {...item, children: checkItems(item.children)}
    : checkItems(item.children)
  );
}

console.log(checkItems(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 best way to change specific elements in an array to 0?

I have come across numerous instances where individuals substitute specific elements in an array with zeroes based on their values. For instance: X = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20] Setting all values < 4 to zero is not what I am looking ...

What are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

inconsistent firing of mousedown events

On my webpage, I am using the following JavaScript code: $("#attach-body").mousedown(function (event) { //alert(event.button); switch (event.button) { case 2: event.preventDefault(); event.stopPropagation(); break; default: ...

Integrating Contact Form with PhoneGap API using JavaScript and HTML5

I am currently working on building a contact form using the PhoneGap API integrated with JavaScript and HTML5 for the form design. The contact form I am creating should allow me to add new contacts and search for existing ones. To achieve this, I have been ...

Guide on invoking the server-side method in Office 365 using JavaScript files

Exploring the capabilities of office 365 API apps and looking for documentation on how to access specific row(s) and cell(s) values / select a particular sheet programmatically in a .js file. Currently, I am utilizing the following code within a function: ...

Whenever I create the code using javascript, padding seems to always show up

I have a basic stacked row layout that displays an upper box and lower box without any padding. <span id="route" class="small"> <div class="row" style="border-style:solid;"> <div class="col-md-12 col-12"> <p>UpperBox</p& ...

What is the connection between Strict Aliasing and the implementation of parallel arrays in a union?

Consider the following union: union { uint16_t halfwords[32]; uint32_t fullwords[16]; } my_union; What does the Strict Aliasing rule state with regards to: my_union.fullwords[0] = 1; printf("%d", my_union.halfwords[1]); Is my_union.halfwords[1] con ...

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

Executing keyboard event in JavaScript that is recognized by pynput

Currently, I am utilizing Python's Bottle framework to run a website and have implemented the keyboard listener from the pynput package. The listener halts when the delete key is pressed, but I am looking to add functionality that allows the listener ...

Tips for defining the operational scope of orbit controls in three.js

I've been working on creating an orientation cube in threeJS and have set up 2 scenes with different viewports, cameras, and controls. Check out the fiddle here var controls = new THREE.OrbitControls( view.camera, container.domElement ); In the fid ...

Attempting to implement a method for comparing integers, but encountering difficulties with its functionality

Currently, I am working with an array of integers and my goal is to identify the highest value within the array and then assign a new integer to that particular value. As someone who is just beginning to learn C programming, I have encountered some challen ...

The function of Durandal is not defined

I seem to be having an issue with Durandal. I followed the documentation but I'm getting an error saying that the function is not defined. What could I be doing wrong? backend.js: define(function(require){ return { getActivePeriods:funct ...

Send a redirect after a certain delay to a URL stored in a variable outside of the current scope

Upon making an ajax request, the JSON response contains a link that needs to redirect the user to another page after 3 seconds. The current approach used is: response = JSON.parse(res); var link = response.link; setTimeout("window.location.href=link",300 ...

Why won't the code for detecting the DEL key in a textarea work on my computer?

I've been trying to detect when a user presses the Delete key and came across this helpful tutorial here The code worked flawlessly on jsfiddle.net, you can check it out here- http://jsfiddle.net. However, when I copied the same code to my local comp ...

Express server experiences empty body when using the Fetch POST method

Executing a POST request from my browser client looks like this: const post = async (url, body) => { try { const response = await fetch(url, { method: `POST`, headers: { 'Conte ...

Swapping out a sequence of characters in a web address with a different set

Swapping out imgur for filmot, Enter URL - https://i.stack.imgur.com/Uguvn.jpg Click the submit button After clicking submit, a new tab should open with the link .filmot.com/abcde.jpg. <html> <head> <title>input</title> <sc ...

Error Alert: Arrays and confusion reign during run-time check failure #2

Currently facing an issue with my code where I am inputting 92 temperatures from a file into 3 arrays. Oddly enough, commenting out the third array resolves a "corruption" problem in one of the other arrays. However, adding the third array back in leads ...

Tips for getting the setTimeout() function to behave like a for loop

Is there a way to achieve the setTimeout() function's behavior in a for-loop? Take a look at this code snippet: function hello() { for (let index = 0; index < 3; index++) { setTimeout(function () { console.log('What&bs ...

Is it possible for an angular directive to transmit arguments to functions within specified expressions in the directive's attributes?

I am working on a form directive that utilizes a specific callback attribute with an isolate scope: scope: { callback: '&' } This directive is placed within an ng-repeat, where the expression passed in includes the id of the object as an ar ...

How can I create a new div element for every item in an array by utilizing JSX?

I am currently working on creating a div element for each item in an array using reactjs JSX. I wasn't sure how to tackle this, so I attempted the following approach: {results.map((element, index) => ( <div key={index} className={ ...