Is there a way to eliminate nested or parent objects from an array using JavaScript?

I am looking for a way to remove an object based on its id without using a MongoDB query. Instead, I want to remove the object from an array stored in a variable using a JavaScript function.

For example, if I provide

id=ObjectId("5b693e7ddd65ec16a46b7f82")
from this object:

 [{
     "commentedBy": "test",
     "subComments": {
         "commentedBy": "jaril 2",
         "subComments": {
             "commentedBy": "jaril 3",
             "subComments": {
                 "commentedBy": "jaril 4",
                 "commentId": ObjectId("5b693e7ddd65ec16a46b7f85")
             },
             "commentId": ObjectId("5b693e7ddd65ec16a46b7f84")
         },
         "commentId": ObjectId("5b693e7ddd65ec16a46b7f83")
     },
     "commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
 }]

the expected output should be an empty array.

[]

Alternatively, if I pass

id=ObjectId("5b693e7ddd65ec16a46b7f83")
, then the output should look like this:

[{
    "commentedBy": "test",
    "commentId": ObjectId("5b693e7ddd65ec16a46b7f82")
}]

I have tried using a recursive function to remove comments but it's not working as expected because we need to pass the key of the comment along with the id.

async.eachSeries(result[0].comments, function (data, cb) {
    function deleteCommentId(comments) {
        if (comments.commentId.valueOf() == req.body.commentId) {
            delete comments
        }

        if (comments.subComments) {
            deleteCommentId(comments.subComments);
        }

        return comments;
    }

    deleteCommentId(data)
    return cb();
}, function () {
    console.log(JSON.stringify(resultFind))
})

If there are 500 sub comments, we should be able to remove any of them based on their ids. Any help or guidance would be greatly appreciated.

Answer №1

Can you please confirm if this solution meets your requirements?

function retrieveComment(commentList, targetId) {
    if (commentList.commentId === targetId || !commentList.subComments) {
        return [];
    } else if (commentList.subComments && commentList.subComments.commentId === targetId) {
        return {
            "commentedBy": commentList.commentedBy,
            "commentId": commentList.commentId
        }
    } else {
        retrieveComment(commentList.subComments, targetId)
    }
}

The initial call should be made as

retrieveComment(commentArray[0], "5b693e7ddd65ec16a46b7f82")

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

Building a loading spinner component in a react-native project

I have successfully implemented a loading spinner that is currently being used in various components of my React project. However, as I am now working on a react-native version of the application, I am faced with the challenge of recreating this loading sp ...

Encountering a TypeError: relativeURL.replace is not a valid function in Next.js

Why am I encountering this error in my Next.js application? TypeError: relativeURL.replace is not a function. (In 'relativeURL.replace(/^/+/, '')', 'relativeURL.replace' is undefined) Request.js file const API_KEY = process ...

I'm encountering an issue when trying to build a React application

Unable to perform EPERM operation, the command "mkdir c:" is not found when trying to create a React app using npx create-react-app myapp ...

Generate an image instantly from text using ajax when a key is pressed

Currently, I am immersed in a stencil project where my goal is to convert text into an image. In this particular task, there's a textbox that captures the user input on key up event. Once the user enters text, my aim is to display that text as an imag ...

Sending an array from JavaScript to PHP and then back to JavaScript

I have a task to transfer an array from one webpage to a PHP page for it to be saved in a file, and then another webpage has to retrieve that array from the file. Currently, I have an array in JavaScript containing all the necessary information: JavaScri ...

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 ...

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Trouble with displaying events on Angular UI-Calendar

I've been working with Angular UI Calendar and following the steps outlined on their website: http://angular-ui.github.io/ui-calendar/ Despite implementing everything correctly, I'm facing an issue where the events fetched from my API are not s ...

Can you explain the significance of "===" and the key distinctions it has from "=="?

Related Query: Javascript === vs == : Does it matter which “equal” operator I use? What is the significance of using === in jQuery/Javascript, and how does it differ from ==? For instance, in my code snippet below: if ($this.val() != &a ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

What is the best way to verify the number of values stored within a variable in JavaScript?

My goal is to calculate the sum of 6 values by inputting them into a single field using a button. To achieve this, I am seeking knowledge on how to determine the number of values contained within a variable. This will allow me to implement an "if" conditi ...

What are the risks and drawbacks of revealing your environment variables to the browser in NextJS?

Currently in the process of setting up Firebase v9 authentication within a NextJS application I am developing. Initially, I attempted to utilize Next's server-side environmental variables for my Firebase configuration but encountered issues with all e ...

Issue: The `libsass` component could not be located

When attempting to run an Express app using node-sass-middleware on Ubuntu, I encountered this error: 0 info it worked if it ends with ok 1 verbose cli [ '/home/mohamed/.nvm/versions/node/v0.12.7/bin/node', 1 verbose cli '/home/mohamed/.n ...

Here's a unique version: "Steps for replacing an outdated chart with a new one using Chart.js and

Is there a way to remove an old chart when the user clicks a button to retrieve a new chart? I understand that the existing chart needs to be destroyed before a new one is generated, but currently, the code does not support destroying non-globally create ...

An Overview of Implementing Ajax Calls for Partial Views on Form Submission

Check out my jQuery code below: <script type="text/javascript"> $("#submitfileform").submit(function () { $.ajax({ type: 'POST', contentType: 'application/html;charset=utf-8', dataT ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

What are some ways to conceal the API connection within a button?

I have a code that allows me to perform a certain API call with a link. Here is an example: <a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain=&ap ...