Remove a single item from a dynamically generated ObjectArray

I am working with an object array list that is formatted like this:

var myFormData = [
{
    id: 1,
    name: "first name",
    type: "test",
    root: "/myfolder"
},
{
    id: 3,
    name: "your name",
    type: "test 2",
    root: "/myfolder2"
}, {
    id: 4,
    name: "your test",
    type: "test 3",
    root: "/myfold",
    child: [
        {
            id: 5,
            name: "name",
            type: "testf",
            root: "/myfoldertr"
        },
        {
            id: 6,
            name: "first-name",
            type: "test",
            root: "/myfolderoot",
            child: [
                {
                    id: 8,
                    name: "sub first name",
                    type: "test5",
                    root: "/myfoldertest"
                }, {
                    id: 9,
                    name: "first name root",
                    type: "test9",
                    root: "/myfolder",
                    child: [
                        {
                            id: 10,
                            name: "normal first name",
                            type: "test5",
                            root: "/myfoldertest"
                        }, {
                            id: 11,
                            name: "last first name",
                            type: "test5",
                            root: "/myfoldertest"
                        }
                    ]
                },
                {
                    id: 12,
                    name: "name Name",
                    type: "testf",
                    root: "/myfoldertr"
                }
            ]
        },
        {
            id: 7,
            name: "first name",
            type: "test",
            root: "/myfolder"
        }
    ]
}]

The structure is generated from a database, so I cannot guarantee the data is always accurate. Sometimes objects have children, sometimes not. My goal is to remove an object with a certain id (obtained programmatically), such as deleting id=11.

Answer №1

One important aspect to note is the necessity to delve deep into the target array. The provided code snippet exemplifies the use of a recursive call to navigate deeply into the nested array.

function deleteObj(target, id) {
  if (!Array.isArray(target)) return;
  target.forEach(function(item, index) {
    if (item.child) {
      target = deleteObj(item.child, id);
    }
    if (item.id === 11) {
      target.splice(index, 1);
    }
  });
}

var myFormData = [{
    id: 1,
    name: "first name",
    type: "test",
    root: "/myfolder"
  },
  {
    id: 3,
    name: "your name",
    type: "test 2",
    root: "/myfolder2"
  }, {
    id: 4,
    name: "your test",
    type: "test 3",
    root: "/myfold",
    child: [{
        id: 5,
        name: "name",
        type: "testf",
        root: "/myfoldertr"
      },
      {
        id: 6,
        name: "first-name",
        type: "test",
        root: "/myfolderoot",
        child: [{
            id: 8,
            name: "sub first name",
            type: "test5",
            root: "/myfoldertest"
          }, {
            id: 9,
            name: "first name root",
            type: "test9",
            root: "/myfolder",
            child: [{
              id: 10,
              name: "normal first name",
              type: "test5",
              root: "/myfoldertest"
            }, {
              id: 11,
              name: "last first name",
              type: "test5",
              root: "/myfoldertest"
            }]
          },
          {
            id: 12,
            name: "name Name",
            type: "testf",
            root: "/myfoldertr"
          }
        ]
      },
      {
        id: 7,
        name: "first name",
        type: "test",
        root: "/myfolder"
      }
    ]
  }
];

function deleteObj(target, id) {
  if (!Array.isArray(target)) return;
  target.forEach(function(item, index) {
    if (item.child) {
      target = deleteObj(item.child, id);
    }
    if (item.id === 11) {
      target.splice(index, 1);
    }
  });
}

deleteObj(myFormData, 11);
console.log(myFormData);

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

Using Jquery to Retrieve the Content of Head and Body Tags from a String

Here is a string that I currently have: <head> This is the Head </head> <body> <div> <div> <p> Body Content <br /></p> <p>&nbsp; Hello World <br />< ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

What causes the auto focus directive to fail to function properly?

I'm having trouble getting the auto focus directive to work. Can anyone take a look at my code? It seems like there might be an issue with it. var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', functio ...

Having trouble retrieving data from an array within a JSON object

I've spent countless hours searching for a solution to this issue, but no matter what I attempt, I keep running into the same error message. The dreaded error I keep encountering is: Fatal error: Cannot use object of type stdClass as array My curren ...

Daily loop countdown timer

Looking to implement a daily countdown timer that ends at 10am, I have the following code set up: setInterval(function time(){ var d = new Date(); var hours = 09 - d.getHours(); var min = 60 - d.getMinutes(); if((min + '').length == 1){ ...

Get the hash value after a specific character using Javascript

I'm currently working on a website with ajax functionality where pages load when clicking on navigation buttons. However, I encounter issues when reloading the page as it defaults back to loading main.html, regardless of the URL. The hash being used i ...

Dynamically obtaining the content of a tag using jQuery

Although this question may have been asked multiple times before, I am encountering a peculiar issue. Let me explain the scenario: Within this tag, there is a dynamically loaded integer: <i id="my_id">{{integer value}}</i> I am attempting t ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

Issues with Pdf.js functionality on Internet Explorer

Could someone shed some light on why this code isn't functioning in Internet Explorer? It works perfectly fine in Chrome. Snippet of my HTML: <head> <script type='text/javascript' src="//code.jquery.com/jquery-1.9.1.js"></sc ...

Attempting to store a specific h1 text.event as a variable, allowing it to be saved upon input of the initial letter

After typing the second key, you can continue to input more characters as desired. It is possible to customize the text displayed in the h1 using your own name or any other text of your preference without needing a textbox. $(document).keypress(functio ...

Instantiate a child class within an abstract class by utilizing the keyword "this"

Within my code, there is an abstract class that uses new this(). Surprisingly, this action is not creating an instance of the abstract class itself but is generating an instance of the class that inherits from it. Even though this behavior is acceptable i ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Getting the specific key of the selected item from material-ui autocomplete when onSelect is triggered, rather than simply retrieving the value

I am incorporating React with Material-ui and utilizing the Autocomplete component described in detail on this page - https://material-ui.com/components/autocomplete/ using downshift. <Downshift id="downshift-options"> ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

Encountering a maximum call stack size error is a common issue when implementing d3.layout.partition in Angular

I recently developed an AngularJS directive to generate a D3 sunburst chart, but I'm encountering issues. I'm receiving a maximum call stack error in Chrome and a too much recursion error in Firefox. After some investigation, I found that the pro ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

Extract information from a lengthy text (vcard)

While scanning data from a vcard QR-code, the string I receive always follows this format: BEGIN:VCARD VERSION:2.1 N:Lastname;Firstname FN:Firstname Lastname ORG:Lol Group TITLE:Project Engineer TEL;WORK:+32 (0)11 12 13 14 ADR;WORK:Industrielaan 1;2250 Ol ...

Implementing a dynamic text field feature with JavaScript and PHP

Field Item                 Field Qty --------                 ----- --------                 ------ --------       ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

What is the best way to store and retrieve a three-dimensional dynamic character array in a file?

Within my code, I have set up an array that looks like this: char ***three_dim=0; Once three_dim has been allocated and filled with data, my next step is to save its contents to a file and then retrieve them later on. However, the method I attempted to u ...