Extract Elements from Nested Arrays

I need assistance with filtering specific items and arrays within a nested array by using the methods .map and .filter.


Below is an example of the given array structure:

items: [
    {
        title: 'dashboard',
        isValidateAccess: false,
    },
    {
        title: 'reports',
        isValidateAccess: true,
        children: [
            {
                title: 'attendancesReportMenu',
                isValidateAccess: true,
            },
            {
                title: 'holidaysReportMenu',
            },
            {
                title: 'absencesReportMenu',
                isValidateAccess: true,
            },
        ],
    },
    {
        title: 'myDepartments',
        children: [
            {
                title: 'inconsistencies',
                isValidateAccess: true,
            },
            {
                title: 'absences',
            },
            {
                title: 'clocks',
                isValidateAccess: true,
            },
            {
                title: 'employees',
            },
        ],
    },
]

The goal is to remove all items/arrays where the property isValidateAccess is set to true. This is how the filtered array should look like:

items: [
    {
        title: 'dashboard',
        isValidateAccess: false,
    },
    {
        title: 'myDepartments',
        children: [
            {
                title: 'absences',
            },
            {
                title: 'employees',
            },
        ],
    },
]

Answer №1

Start by using the filter() method on the main array to eliminate the top-level elements. Then, iterate through the remaining elements using the forEach() method to filter out the arrays within the children property.

let items = [{
    title: 'home',
    isLocked: true,
  },
  {
    title: 'profile',
    isLocked: false,
    children: [{
        title: 'settings',
        isLocked: true,
      },
      {
        title: 'privacy',
        isLocked: false,
      },
      {
        title: 'security',
        isLocked: true,
      },
    ],
  },
  {
    title: 'notifications',
    children: [{
        title: 'email',
        isLocked: false,
      },
      {
        title: 'sms',
        isLocked: true,
      },
      {
        title: 'push',
        isLocked: false,
      },
    ],
  },
];

items = items.filter(item => !item.isLocked);
items.forEach(item => item.children && (item.children = item.children.filter(child => !child.isLocked)));

console.log(items);

Answer №2

Check out this innovative approach

const itemList = [
    {
        name: 'inbox',
        isAccessible: false,
    },
    {
        name: 'tasks',
        isAccessible: true,
        children: [
            {
                name: 'completedTasks',
                isAccessible: true,
            },
            {
                name: 'pendingTasks',
            },
            {
                name: 'overdueTasks',
                isAccessible: true,
            },
        ],
    },
    {
        name: 'myProjects',
        children: [
            {
                name: 'activeProjects',
                isAccessible: true,
            },
            {
                name: 'archivedProjects',
            },
            {
                name: 'upcomingProjects',
                isAccessible: true,
            },
            {
                name: 'completedProjects',
            },
        ],
    },
]
const customFilter = (filterable) =>
  filterable
  .filter(item => !item.isAccessible)
  .map(item => ({
    ...item,
    children: item.children?.filter(i => !i.isAccessible)
  }))


  
console.log(customFilter(itemList))

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

Issue with ThreeJs raycaster not returning correct event.clientY value when header bar is visible

Here's the issue: I'm trying to place a sphere on a 3D model when I click on it using ThreeJs raycaster. It works fine when the canvas covers the entire page, but if I add a header bar to the page, the positioning is off. Here are some visual ex ...

AngularJS complications with data flow

I am facing an issue in my code where I have a function nested inside a directive that fetches query results successfully. However, I am struggling to store these results in a factory and then pass them to a controller. Below is the code snippet of the di ...

What's the best way to keep track of the number of objects I've created

Using this HTML code, I can create member objects. However, I also need to determine the count of these member objects for certain calculations. Additionally, when a member object is deleted, the count of member objects should be reduced accordingly. The ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

Programmatically control the opening and closing of a React Material UI Snackbar component

Currently, I am facing some challenges while working on programming a Single Page Application (SPA) using React and Material-UI. In my project, I have created a modal login box that gets triggered by a button on the navigation bar. Upon clicking submit, I ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'. The function works correctly in one example, but not in another. Can you help me identify what mistake I made? String.proto ...

Event listener for clicking on a custom overlay in Google Maps

Incorporating Google Maps into an Ionic project, I have successfully added a custom overlay to display the address of a marker location on top of the map. By adding a click event listener to the map, I can detect clicks and update the marker for new locat ...

collecting user input in React.js

After doing some research on React.js from this website, I stumbled upon a piece of code that left me puzzled. As far as I can tell, the checkbox for isGoing will be pre-filled as true (checked) and the numberOfGuests will be set to 2. However, I found m ...

Error: npm encountered a socket timeout issue

Setting up a fresh React application in /home/abhijith/Desktop/React/firstReact/myapp. Installing necessary packages. This process may require a few minutes. Installing react, react-dom, and react-scripts along with cra-template... npm ERR! code ERR_SOCK ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Creating a fairness algorithm with circular arrays in Javascript: A step-by-step guide

My child's baseball team consists of 13 players. In order to ensure that each player has an equal opportunity to play different positions, I devised a JavaScript algorithm. However, the current algorithm does not seem to be distributing the positions ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

Using Ruby on Rails to incorporate AJAX for posting and commenting functionality

Could use some assistance with implementing AJAX into my project. It seems like it should be a simple task, but I've been struggling with it for days. My goal is to have new comments appear without the need to reload the page. Below are references to ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Two draggable elements and two droppable containers all conveniently placed on a single webpage

My current project involves two sets of draggable elements and two sets of droppable elements. I'm trying to achieve a specific functionality where the first set of draggable elements can only be dropped inside the first set of droppables, while the ...

Guide to sending a POST request from within my application

I'm facing an issue with using $resource for making a post request in my app. Here is the code snippet from my Angular module: angular.module('myApp').factory('Product', ['$resource', function ($resource) { ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

Style binding for background image can utilize computed properties or data for dynamic rendering

In my code, I am trying to pass an object that contains a string path for its background image. I have experimented with using data and computed properties, but so far I haven't had any luck getting them to work within the :style binding. However, if ...