Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below:

const obj = [
    {
        "description": "PCS ",               
        "children": [
            null,
            {
                "name": "Son",
                "children": [
                    {        
                        "name": "Son2",               
                        "children": [],                        
                    },
                    {
                        "name": "Son3",               
                        "children": [],
                    }
                ],
            },
            {
               "name": "Son4",
                "children": [
                    {        
                        "name": "Son4",               
                        "children": [],                        
                    },
                    {
                        "name": "Son4",               
                        "children": [],
                    }
                ],
            },
            {
                "name": "Son",
                "children": [
                    {        
                        "name": "Son2",               
                        "children": [
                            {
                                "name": "More"                                
                                "children": [
                                    null,
                                    {
                                        ...other objects
                                    }
                                ],                                
                            }
                        ], 
                    },
                ],
            },            
        ],
    },
    {
        "name": "awesome",
        "children": [
            {                
                "children": [],             
                "active": true
            }
        ],
    },
    {
        "name": "children",
        "children": []
    },
]

My aim is to eliminate all occurrences of null within the children's arrays. The issue lies in the nested nature of the arrays, as there could be multiple levels of nesting containing null elements.
I attempted using a recursive function which wasn't successful:

function deactiveRecursive(obj) {
    if (!obj) return;
  return {
    ...obj,    
    children: obj.children.filter(child => child !== null)
  };
}

function removeRecursive() {
    return obj.filter((item) => {        
        return {
            ...item,
            children: item["children"].filter((c) => deactiveRecursive(c))
        }
    })
}

I have previously applied a similar approach to remove an item based on a specific id (it worked, but I wanted to completely remove the objects instead of returning null or undefined). However, due to the necessity of having a return value, I couldn't simply erase it. This logic resulted in the objects being replaced with null.

const deact = JSON.stringify(
        this.array,
        (_, nestedValue) => {
          if (nestedValue && nestedValue['_id'] === MyWanteIdToRemove._id) {
            return null
          }
          return nestedValue
        }
      )

Answer №1

One way to recursively modify an object in-place is by using the splice method to remove null values from arrays.

const obj = [
    {
        "descricao": "PCS",
        "children": [
            null, null, null,
            {
                "name": "Son",
                "children": [
                    null, null, null,
                    {
                        "name": "Son2",
                        "children": []
                    },
                    null, null, null,
                    {
                        "name": "Son3",
                        "children": []
                    },
                    null, null, null
                ]
            },
            null, null, null,
            {
               "name": "Son4",
                "children": [
                    null, null, null,
                    {
                        "name": "Son4",
                        "children": []
                    },
                    null, null, null,
                    {
                        "name": "Son4",
                        "children": []
                    },
                    null, null, null
                ]
            },
            null, null, null,
            {
                "name": "Son",
                "children": [
                    null, null, null,
                    {
                        "name": "Son2",
                        "children": [
                            null, null, null,
                            {
                                "name": "More",
                                "children": [
                                    null, null, null,
                                    { "other": "objects..." },
                                    null, null, null
                                ]
                            },
                            null, null, null
                        ]
                    },
                    null, null, null
                ]
            },
            null, null, null
        ]
    },
    null, null, null,
    {
        "name": "awesome",
        "children": [
            null, null, null,
            {
                "children": [ null, null, null ],
                "ativa": true
            },
            null, null, null
        ]
    },
    null, null, null,
    {
        "name": "children",
        "children": [ null, null, null ]
    },
    null, null, null
];

function removeNulls (object) {
    if (typeof object == 'object' && object != null) {
        if (Array.isArray(object)) {
            for (let i = 0; i < object.length; i++) {
                if (object[i] === null) {
                    object.splice(i--, 1);
                }
                else {
                    removeNulls(object[i]);
                }
            }
        }
        else if (object.children) {
            removeNulls(object.children);
        }
    }
}

removeNulls(obj)
console.log(obj);

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

The concept of recursion in AngularJS directives

I developed a unique custom directive. angular.module('menu',[]) .directive('MenuDirective',function(){ return{ restrict:'E', replace:'true', scope:{ m ...

Efficiently assign multiple attributes using a single d3 function

Hey everyone! I'm currently working with SVG lines and have come across an example object that looks like this: { _id: 5, coordinates:{ x1: 100, y1: 100, x2: 500, y2: 500, } Now, imagine I have an array of these obje ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

Angularjs application and bash script generating different SHA256 hashes for the same file

In my AngularJS app, I am struggling to get the digest of an uploaded file. The issue is that the resulting hash is not matching the one obtained using bash locally. Initially, I used jshashes, but when I noticed discrepancies in the hashes generated by t ...

Customize the default directory for local node modules installation in node.js using npm

If I prefer not to have my local (per project) packages installed in the node_modules directory, but rather in a directory named sources/node_modules, is there a way to override this like you can with bower? In bower, you specify the location using a .bow ...

What is the best way to ensure that cleanup is always executed at the conclusion of a function

Imagine a scenario where I have the following function (psuedo-code) : function Foo() { let varThatNeedsCleanup = //something if(condition1) { return Error1; } if(condition2) { return Error2; } if(condition3) { return Error3; ...

Discovering the exact distance between a 'li' and a 'div' element

Currently, I am in the process of converting HTML to JSON. Here is an example of the HTML I am working with: <div class="treeprofit" id="divTreeViewIncomeDetails" style="height: auto;"> <li><span class="fa fa-folder-open highlight" ...

Activate a button on-the-fly

When the page loads, I have an empty array. Since there are no values stored in this array, I disabled the button using ng-disabled="array1.length==0". Now, on the page that opens up, there are four drop downs present. My goal is to enable the button once ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

Codeigniter - Ajax request successful in remote server but fails in local server

I am encountering an issue with my web application that makes Ajax requests to a server using Codeigniter-php code. While the Ajax requests work fine on the local server, they do not function properly when the application is hosted on a remote server. The ...

Exploring the possibilities of integrating JavaScript with Flash technology

Currently, there is a simple Flash project in development that connects to an RTMP server and streams video and audio from a webcam. The project allows users to create a stream with a specific name. This project also features an input for entering a strea ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

Access the session on both routers

I currently have 2 different routers set up in my application: Router 1 app.post('/consultations', function(req, res) { req.session.name = 'administrator'; console.log('test', req.session.name); // the session is pro ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...

Error Encountered When Running JavaScript Code

Running the code on my Localhost:3000 is resulting in an error message: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'id') The specific section of the code causing this error is highlighted in the Source part: ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...