Filtering an array of parent elements in Javascript based on a specific value found in

Trying to filter data from a 3-layer array based on child array values. Making progress but hitting a roadblock at the end.

{
    "id": 1,
    "grandparent": "Timmy",
    "parents": [
        {
            "id": 1,
            "parent": "Johnny",
            "children": [
                {
                    "id": 1,
                    "child": "Sam",
                    "checked": true
                },
                {
                    "id": 1,
                    "child": "Ted",
                    "checked": false
                }
            ]
        },
        {
            "id": 2,
            "parent": "Jessica",
            "children": [
                {
                    "id": 1,
                    "child": "Sam",
                    "checked": false
                }
            ]
        },
    ]
}

Current code snippet:

    grandparents.value = value.value.map((el) => ({
        ...el,
        parents: el.components.filter((parent) => parent.children?.some((child) => child.checked))
    }))

Current output:

{
    "id": 1,
    "grandparent": "Timmy",
    "parents": [
        {
            "id": 1,
            "parent": "Johnny",
            "children": [
                {
                    "id": 1,
                    "child": "Sam",
                    "checked": true
                },
                {
                    "id": 1,
                    "child": "Ted",
                    "checked": false
                }
            ]
        }
    ]
}

Successful filtering of the parents array, now aiming to also filter out unchecked children.

Desired results

{
    "id": 1,
    "grandparent": "Timmy",
    "parents": [
        {
            "id": 1,
            "parent": "Johnny",
            "children": [
                {
                    "id": 1,
                    "child": "Sam",
                    "checked": true
                }
            ]
        }
    ]

Answer №1

filter() function will specifically add or remove the object without modifying the inner children array.


An alternative approach could be using the reduce() method where:

  1. for each parent, filter out the children
  2. if a child is found, update the object with the filtered children array
  3. otherwise, exclude this particular parent

let data = {"id": 1, "grandparent": "Timmy", "parents": [{"id": 1, "parent": "Johnny", "children": [{"id": 1, "child": "Sam", "checked": true }, {"id": 1, "child": "Ted", "checked": false } ] }, {"id": 2, "parent": "Jessica", "children": [{"id": 1, "child": "Sam", "checked": false } ] } ] };

data.parents = data.parents.reduce((previous, current) => {
  const children = current.children.filter(child => child.checked);
  if (children.length) {
      return [ ...previous, { ...current, children } ];
  }
  return previous;
}, []);

console.log(data);


{
  "id": 1,
  "grandparent": "Timmy",
  "parents": [
    {
      "id": 1,
      "parent": "Johnny",
      "children": [
        {
          "id": 1,
          "child": "Sam",
          "checked": true
        }
      ]
    }
  ]
}

Answer №2

Iterate through the ancestors list, and for each ancestor, we will only keep the descendants who are marked as checked. Then, we will use the filter() method again to eliminate any ancestors whose descendant list becomes empty after filtering.

const data = {
    "id": 1,
    "ancestor": "Timmy",
    "ancestors": [
        {
            "id": 1,
            "parent": "Johnny",
            "descendants": [
                {
                    "id": 1,
                    "descendant": "Sam",
                    "checked": true
                },
                {
                    "id": 1,
                    "descendant": "Ted",
                    "checked": false
                }
            ]
        },
        {
            "id": 2,
            "ancestor": "Jessica",
            "descendants": [
                {
                    "id": 1,
                    "descendant": "Sam",
                    "checked": false
                }
            ]
        },
    ]
}

const filteredData = {
  id: data.id,
  ancestor: data.ancestor,
  ancestors: data.ancestors.map((ancestor) => ({
    id: ancestor.id,
    parent: ancestor.parent,
    descendants: ancestor.descendants.filter((descendant) => descendant.checked)
  })).filter((ancestor) => ancestor.descendants.length > 0)
};

console.log(filteredData)

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

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

Finding distinct elements in two NumPy arrays

Seeking assistance with manipulating an array retrieved from a table: lycop = np.array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [1, 1, 8, 24, 48, 58, 35, 16, 8, 1]]) lycop array([[14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [ 1, ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

RecyclerView refuses to refresh under any circumstances

After loading the questions and answers properly, my RecyclerView is not updating even when I call adapterNotifyDataSetChanged(). The items in the recycler view remain unchanged and are not even reordered. This issue is occurring in my MainActivity class ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

The combination of loading and scrolling JavaScript code is not functioning properly on the website

I created an HTML webpage that includes some JavaScript code to enhance the user experience. However, I encountered an issue when trying to incorporate a load JavaScript function alongside the scroll JavaScript function on my page. The load script is posi ...

Executing a Python function on a server from a local machine with the help of AngularJS

I am encountering an issue with calling a python function using an angularjs $http request. The python function I have on the server looks like this: import cgi, cgitb data= cgi.FieldStorage() name = data.getvalue("name"); age = data.getvalue("age"); def ...

What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relati ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...

Increasing numerical values within an array using JavaScript

My goal is to enhance the functionality of this visualization by being able to increase or decrease the nodes in the hidden layers. I have attempted to achieve this by adding the following code: I am facing difficulties in adjusting the number of hidden l ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Positioning Firefox absolutely within a table-cell element is possible

Interestingly, it's not Internet Explorer causing me trouble this time, but Firefox. Here is the Fiddle link for reference: http://jsfiddle.net/EwUnt/ The purpose of this table is to highlight both the row and column of the cell where the cursor is ...

Creating dynamic routes for every page fetched from the API in Next.js

Hello everyone, Recently, my journey with NodeJS just commenced and I have been exploring API routes in NextJS as it provides an easy setup and clear visibility of the processes. While I have a grasp on creating basic get requests, I am now intrigued by s ...

Enhance the Vue.js performance by preloading components

After discovering the benefits of lazy loading components, I decided to start implementing it in my project. However, I encountered some issues when trying to prefetch the lazy loaded components and vue-router routes. Upon inspecting with Chrome DevTools, ...

Breaking the loop with a simple statement

I'm unsure if anyone will notice if I make changes to my preceding post, so I am here now to create a new one. Below is the code snippet: $(document).ready(function(){ var a; var b; var c; var d; var pmmain = ["Citrix", "Coach", ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Is there a way to keep the node text in place and prevent overlapping in my D3.js tree?

I'm facing an issue with long text strings in my D3 tree. The nodes move according to the tree structure, but how can I handle excessively long node-text? For instance, if the label "T-ALL" had a longer name, it could overlap with the neighboring nod ...