Filtering nested objects in JavaScript up to a specific level

I need to implement a filter for an array of nested objects in JavaScript.

After researching, I found the following solution from another source.

var sampleData= [{       
        "rowId": "3.0.0",
        "startDate": "2020-10-20",
        "subTasks": [                 
            {                
                "rowId": "3.3.0",
                "startDate": "2021-05-26",             
                "subTasks": [
                    {
                        "rowId": "3.3.0.1",
                        "startDate": "2021-05-26",                        
                        "subTasks": []
                    },
                    {
                        "rowId": "3.3.0.2",
                        "startDate": "2021-06-09",
                        "endDate"": "2021-07-23",
                        "subTasks"]<span></span>: []                      
                    },                   
                ]
            },           
        ]
    }]

    filtered = sampleData.map(element => {
        return {
          ...element,
          subTasks: element.subTasks.filter(subElement => {
            return subElement.endDate
          })
        }
      })  
      console.log("sampleData",JSON.stringify(filtered))




The goal is to filter based on the end date. Expected result: Object with rowId "3.3.0.2" should be filtered out.

This current implementation only filters up to 2 levels deep. However, considering that my nested objects can extend up to 10 levels, how can I apply this filtering across any number of levels?

Answer №1

If you want to achieve this, you can utilize a recursive function that loops through only the valid subtasks. Assuming you are familiar with how recursive functions work, here is an example:

function filterSubTasks(elem) {
  const filteredSubTasks = elem.subTasks
    .filter(subTask => !subTask.endDate)
    .map(subTask => filterSubTasks(subTask))
  
  return {
    ...elem,
    subTasks: filteredSubTasks
  }
}

Simply call the function like this:

sampleData.map(elem => filterSubTasks(elem))

var sampleData= [{       
        "rowId": "3.0.0",
        "startDate": "2020-10-20",
        "subTasks": [                 
            {                
                "rowId": "3.3.0",
                "startDate": "2021-05-26",             
                "subTasks": [
                    {
                        "rowId": "3.3.0.1",
                        "startDate": "2021-05-26",                        
                        "subTasks": []
                    },
                    {
                        "rowId": "3.3.0.2",
                        "startDate": "2021-06-09",
                        "endDate": "2021-07-23",  
                        "subTasks": []                      
                    },                   
                ]
            },           
        ]
    }];

function filterSubTasks(elem) {
    const filteredSubTasks = elem.subTasks
    .filter(subTask => !subTask.endDate)
    .map(subTask => filterSubTasks(subTask))
  
  return {
    ...elem,
    subTasks: filteredSubTasks
  }
}

console.log(sampleData.map(elem => filterSubTasks(elem)));

Answer №2

One way to achieve this is through the use of recursion. The values array stores all tasks, which allows for filtration based on any desired property.

var values = [];
function FetchValues(samples){

    if(samples != [] && samples != undefined && samples != null){
        for(var sample of samples){       
            values.push(sample)
            FetchValues(sample.subTasks)
        }
    }else{
        return {};
    }

}
FetchValues(sampleData)

Answer №3

If you would like to apply a filter based on the endDate parameter, one approach is to utilize the forEach method to iterate through the data and store the desired results in an object. This method should help achieve the desired output effectively.

var sampleData= [{       
    "rowId": "3.0.0",
    "startDate": "2020-10-20",
    "subTasks": [                 
        {                
            "rowId": "3.3.0",
            "startDate": "2021-05-26",             
            "subTasks": [
                {
                    "rowId": "3.3.0.1",
                    "startDate": "2021-05-26",                        
                    "subTasks": []
                },
                {
                    "rowId": "3.3.0.2",
                    "startDate": "2021-06-09",
                    "endDate": "2021-07-23",  
                    "subTasks": []                      
                },                   
            ]
        },           
    ]
}]

sampleData.forEach((obj)=> {
   obj.subTasks.forEach((prop) => {
       const newObj = {name: prop};
       console.log(newObj.name.subTasks[1]);
       console.log(newObj.name.subTasks[1].endDate);
   })
})

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

Is there a way to extract the year, day, minute, hour, and second from the Date.now() function in Node.js?

Figuring out how to interpret Date.now() has been challenging for me. I understand that it returns the time in milliseconds since the unix epoch (January 1st, 1970), but I'm struggling to use this information to determine the current date and hour. An ...

Downloading an array as a CSV file using PHP

Struggling to convert my PHP array into a downloadable CSV file. Here's how the array currently looks: Array[0] = "Name,age,ID" Array[1] = "Alex,26,1" Array[2] = "Ryan,12,2" Array[3] = "Steph,56,7" and so on... I attempted to download it as a CSV ...

Updating the Background Image Based on Text Input in JavaScript

Struggling to utilize the text entered into a text input field as a background image URL. Ensuring it is valid is key. This snippet displays what has been attempted so far... CSS: body { margin: 0px; padding: 0px; border: 0px; } .bgimg { backgr ...

How to Retrieve the Id of an Inserted Document in Node.js and MongoDB

When trying to insert data from nodejs to mangodb, I successfully added a document to the database. However, I am unsure of how to retrieve the ID upon successful insertion. Is there a way to obtain the ID once the insert is successful? This snippet is fr ...

"In strict mode, the object is subjected to specific rules

I am facing a challenge with an object in my project that needs to run the content of the page within strict mode. Even after attempting to return it for global scope usage, I still haven't been able to resolve the issue. (function($) { "use stric ...

"Exploring the power of AJAX, manipulating strings with JavaScript, and building

In the process of creating a pyramid web app, I am currently working on integrating the JavaScript markdown editor EpicEditor for editing markdown files. $.ajax({ url: "{{ request.resource_url(context) }}raw_markdown", context: document.body, ...

Using PHP to submit a form depending on user selection

Currently, I am working on a basic input form page that includes a submit button. The goal is to have the data from the form written into my MySQL database based on the user's selection. For instance, if the user chooses option X, I want the input da ...

Tips for stopping the Print dialog box in Mozilla when using the CTRL + P shortcut

When I press CTRL + P on my view, a JavaScript code is triggered. The code works perfectly on all browsers except Mozilla; I cannot seem to block the Print Dialogue on that browser. Is there something wrong with my code? I have been attempting to implemen ...

Using JQuery's .mouseover and .mouseout methods to modify font colors on a webpage

Hi there, I'm new to JQuery and trying to experiment with some basic functionalities. I have a simple navigation menu created using an unordered list, and I want to change the font color of the currently hovered list item using JQuery. However, I&apos ...

Using node.js and expressjs, developers can easily incorporate flash messages into

Could anyone please help me with retrieving flash messages from an express app? I believe that flash messages in express (e.g. req.flash('info', message)) are kept on the server and only displayed in the view upon the next request. Is this corre ...

Is there a way to efficiently retrieve distinct values from each item within the axios response object and store them in a vuex state?

My head is spinning! After making an axios call, I am now staring at a massive JSON array object in the console - Check! >(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, { ...

Discovering the `findIndex` malfunction in Internet Explorer

Having just finished a small form, I realized that my current implementation of findIndex is not compatible with IE. Let's take a look at an example of the problem: var people = [ {name:"Mike", age:"25"}, {name:"Bill", age:"35"}, {name:"Terry" ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

Make sure that the click event listener is set up on the anchor element so that it also affects its children

Currently, I have implemented a click event listener on my anchor elements. However, the anchors contain a span element within them, and the event listener does not function properly if you click on the span inside the anchor. document.addEventListene ...

Angular's Components and Directives: A Comprehensive Guide

My goal is to render a subview within a template and define the state inside the subview's controller when an element is clicked. I am separating it from the main controller because there will be further subviews within this initial subview. However, ...

React application functions correctly on local environment, however encounters an issue during deployment on Heroku

I'm struggling to make this work for me, even though I know it has been solved before. Locally, my repository functions fine with the following as my /index.js const express = require("express"); const keys = require("./config/keys"); const path = ...

How can I effectively exclude API keys from commits in Express by implementing a .gitignore file?

Currently, my API keys are stored in the routes/index.js file of my express app. I'm thinking that I should transfer these keys to an object in a new file located in the parent directory of the app (keys.js), and then include this file in my routes/in ...

javascript batch insert new key values

Is there a more elegant way to set multiple keys of an array in JavaScript? The current code may not be aesthetically pleasing, but it seems to be the only solution that works. var listData = []; listData['today'] = []; listData['data1&a ...

Is there a particular array function that can help me achieve the desired outcome?

Is there a specific array function that can help me achieve the desired outcome? My current array $a = array( [0] => array( 'id' => 6 ), [1] => array( 'id' => 5 ), [2] => array( 'id' => 8 ), [3] => array ...

When the JavaScript string retrieved from the database is null, it will be displayed as an empty string

Currently, my Ajax setup involves querying a database on the server with SELECT someColumn FROM someTable. The returned value of someColumn is then updated on the client side by using $('#someElement').text(someColumn); Everything works perfectl ...