Sort through a never-ending series of nested objects

Consider an array of nested objects like the following:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[
                    {
                        id: 3,
                        children:[
                            {
                                id: 4,
                                children: [],
                            },
                            {
                                id: 5,
                                children: [],
                            }
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

If you want to create a new array with id: 3 excluded, the resulting array should be like this:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

You can exclude an id from any level, and the id along with its children should be eliminated. Do you need advice on the best approach to achieve this? Feel free to share any unsuccessful attempts you have made so far.

Answer №1

To tackle this problem, consider utilizing recursion in combination with the `Array.reduce` method.

For instance:

const data=[{id:1,children:[{id:2,children:[{id:3,children:[{id:4,children:[]},{id:5,children:[]}]},]},]},{id:8,children:[{id:9,children:[{id:10,children:[]},]},]},]


function removeId(data, id) {
  return data.reduce((a,v) => {
    if (v.id !== id) 
       a.push({...v, children: removeId(v.children, id)});
    return a;
  }, []);
}

const r = removeId(data, 3);

console.log(r);

Answer №2

To access each node of the object, a combination of JSON.parse and JSON.stringify can be used:

JSON.parse(JSON.stringify(data, (key, value) => {
   // Removes any child with an id of 3 from the children array
   if (key === 'children' && value instanceof Array) return value.filter(x=>x.id!==3);
   // Leaves other properties unchanged
   return value;
}));

For example:

const data = [
    {
        id: 1,
        children:[
            {
                id: 2,
                children:[
                    {
                        id: 3,
                        children:[
                            {
                                id: 4,
                                children: [],
                            },
                            {
                                id: 5,
                                children: [],
                            }
                        ],
                    },
                ],
            },
        ],
    },
    {
        id: 8,
        children:[
            {
                id: 9,
                children:[
                    {
                        id: 10,
                        children:[],
                    },
                ],
            },
        ],
    },
];

console.log(JSON.parse(JSON.stringify(data, (key, value) => {
   if (key === 'children' && value instanceof Array) return value.filter(x=>x.id!==3);
   return value;
})));

Using the native browser implementation of the JSON methods, this approach is typically faster.

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 program keeps encountering the issue of returning undefined while attempting to calculate the sum of elements in an array

I'm having trouble with the code below, it seems to be returning undefined for the sum of the array. Any advice or assistance would be greatly appreciated. var myExpenses = []; var total; function appendExpenses() { ...

Refreshing the page resolves unhandled errors that occur when an item is removed from local storage

I'm currently working on adding a logout button to my website. I have the user's token saved in local storage, but when the logout button is clicked and the token is removed from local storage, an error occurs upon redirecting back to the login p ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

Adapting iFrame height to accommodate fluctuating content height in real time (details included)

I have an embedded iframe that contains a form with jQuery validation. When errors occur, the content height of the iframe increases dynamically. Below is the script I use to adjust the height of my iframe based on its content: function doIframe(){ o = d ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element. ...

What is the best way to explore JavaScript text using Firebug?

The search function (magnifying glass) located at the top-right hand corner of Firebug does not have the capability to search within JavaScript blocks. For instance, if I have the following code snippet: <script type="text/javascript"> var fooBa ...

Newbie: Troubleshooting Vue Errors - "Vue is not recognized"

I'm currently at the beginning stages of learning Vue and am practicing implementing it. However, I keep encountering the errors "vue was used before it was defined" and "Vue is not defined". Below are excerpts from my HTML and JS files for reference. ...

What is the best way to save data in order to effectively showcase a collection of images that together form a single entity in a game

Apologies for the unclear title, I struggled to find the right words. Recently, I delved into the world of 2D game development and was amazed by the capabilities of HTML5's Canvas element. Currently, I am working on my first basic project to grasp th ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

Content that moves with a flick of a finger

Seeking advice on a widely used JavaScript library that can facilitate scrolling for frequently updated content, similar to what popular websites like have implemented. I've had difficulty finding the right query on Google, so any recommendations or ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

How can I combine multiple textures from mtlLoader and objLoader in three.js?

I have the files .mtl, .obj, and several .jpg textures. I have been attempting to use different textures in the export loader OBJ, and while I can see my object on the scene, it appears as a black color. Can anyone spot what might be incorrect or missing ...

"Exploring the seamless integration of easyXDM, AJAX, and En

In this new inquiry, I am facing a similar challenge as my previous query regarding loading a PHP file into a cross-domain page with dynamic element height. However, I am now exploring a different approach. Although I have managed to load my script into a ...