Filtering array of nested objects in JavaScript up to ‘n’ levels

I want to filter the array of nested objects in javascript. I got the below … Read more Filtering array of nested objects in JavaScript up to ‘n’ levels

I want to filter the array of nested objects in javascript.

I got the below answer from other question.

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": []                      
                    },                   
                ]
            },           
        ]
    }]

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




I want to filer based on the end date.
Expected output: Object with rowId "3.3.0.2" need to be filtered.

This code is filtering only up to 2 levels. But in my case the nested objects can grow up to 10 levels. How can I filter the array of objects up to n levels?

Source: JavaSript – Stack Overflow



Leave a Reply

Your email address will not be published. Required fields are marked *