typescript remove an object array based on the parent key

Let's assume we have a variable called `mylist`

  this.mylist.push([{key:{"test1":name,"test":desc,"hi i am a test":other,"none":type,"amount":0} }]);

This data will be added to the `mylist` array. However, under certain conditions, I want to remove the newly created list by deleting it using its unique key.

To achieve this, I need to splice the object array in order to remove the specific value and avoid duplicates.

I attempted to remove the item like this:

this.mylist.splice(this.mylist.indexOf(key), 1);

Unfortunately, this approach didn't work as expected. I aim to eliminate the array based on the unique key that holds these sub values.

I also made an attempt with the following code:

      this.mylist.splice(this.mylist.indexOf([{key}]), 1);

If anyone could provide support, I would greatly appreciate it :(

      CheckBox(values,values,values) {

        this.bool = (this.mylist.indexOf(key) === -1);


        if (this.bool) { 
          this.mylist.push([{key:{"key":key,"naam":naam,"beschrijving":beschrijving,"type":type,"aantal":aantal} }]);
        }

        else {
this.mylist.splice(this.mylist.indexOf(key), 1);

        }
      }

The above function is triggered when a user clicks on a checkbox. If the condition is met (`true`), the array should be populated with values. Otherwise, the array containing the unique key should be removed to prevent duplicate entries.

Answer №1

Once the push statement is executed, the contents of this.mylist will consist of an array of arrays. This is because you have pushed


    [{key:{"test1":name,"test":desc,"hi i am a test":other,"none":type,"amount":0} }]
which forms an array. In this scenario, accessing the array with the key is not possible (e.g., you cannot access this.mylist[0] by using this.mylist.indexOf(key))

An alternative solution could be to change the type of mylist to an object instead of an array. By doing so, you can add elements to the Object in this manner

[{key:{"test1":name,"test":desc,"hi i am a test":other,"none":type,"amount":0} }];

this.mylist.key = {"test1":name,"test":desc,"hi i am a 
test":other,"none":type,"amount":0} }

Later on, you can utilize the checkbox function like this

CheckBox(values) {
    this.bool = (this.mylist.key === -1);
    if (this.bool) { 
        this.mylist.key={"key":key,"naam":naam,"beschrijving":beschrijving,"type":type,"aantal":aantal};
    } else {
        delete this.mylist.key; 
    }
}

The logic implemented within the Checkbox function appears flawed, as it checks for the presence of a key in mylist. If the key is absent, it adds the key to mylist, and removes it if already present. This logic may not adequately handle the elimination of duplicates if that is your intended outcome.

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 Selenium with C# to find elements within a chart

I am trying to locate and interact with the stimulusFrequency circles on this chart so that I can click and drag them. <svg class="svg-graph-content graphEventHandler ng-valid" ng-model="hearingGraph" viewBox="0 0 470 355" preserveAspectRatio="none"> ...

Is it possible to update the parent state from a child component using the useEffect hook in React?

In a child component, there are buttons that, when clicked, toggle corresponding state values between true and false. This child component also contains a useEffect hook with dependencies on all these state values. When a button is clicked, the hook calls ...

Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file: cons ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

Unidentified object type detected - Material UI

This snippet of code was taken directly from the React Material UI website <Select id="selectedSubusecases" multiple value={stepsState.campaignOverviewStep.selectedSubUsecases} ...

Transform a list of objects into an array

I am currently working on a project that requires me to generate questions randomly in order to create a question paper. To achieve this, I have created a class called Gene to represent a question. I then created a list called QuestionList of type Gene, wh ...

Conceal content after a specific duration and display an alternative in its position, continuously repeating the loop

Imagine creating a captivating performance that unfolds right before your eyes. Picture this: as soon as the page loads, the initial text gracefully fades away after just three seconds. In its place, a mesmerizing animation reveals the second text, which ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

Locate the Highest Number within a Multi-Dimensional Array and Store it in a Fresh Array

I'm currently tackling a coding challenge that involves working with nested arrays. The task is to find the largest number in each sub-array and then create a new array containing only the largest numbers from each one. Initially, my approach was to d ...

Having trouble getting the React Bootstrap Accordion to function properly within NextJS

I recently transitioned my application from CRA to CNA and everything is running smoothly, except for the Bootstrap Accordion which is not functioning properly. Despite trying various methods, I am still unable to resolve this issue. Error Message: Error ...

backbone.js router failing to recognize URL fragments

I have set up a basic router in my code and initialized it. Issue: I encountered an unexpected behavior when visiting the URL http://localhost/backbone1/#photos/5. Despite expecting an output from console.log() in the JavaScript console, nothing appears. ...

What is the best way to instruct Javascript to target the second element using an ID that is not unique?

I need to define a paired list within my automation framework by passing two parameters, the DOM ID of the "Available" items list and the DOM ID of the "Selected" items list. var pairedList: newPairedList("availableItemsListID", "selectedItemsListID"); I ...

When trying to declare i2c_msg, gcc throws an error stating: the array type has an incomplete element

I am currently working on creating wrapper files for i2c communication using C language. Here is a snippet of the header file: #ifndef IMX6QI2C_WRAPPER_H_ #define IMX6QI2C_WRAPPER_H_ #include <linux/i2c-dev.h> //includes definitions for: ...

There appears to be a syntax error with the token "="; an expression is expected to follow this token

I can’t seem to figure out why I am receiving an error message when executing the following code snippet: public void generate2DArray(ArrayList<String> mapArray, int lineNumber) { lineNumber = lineNumber - 2; String [] elementSplit = null; ...

Utilizing model associations in Sails.js to populate an array

I am currently using "sails": "~0.10.0-rc5", "sails-mongo": "^0.10.0-rc3". I have two models: Invoice and Item. Invoice model Invoice: { name: 'sample 1', items: [1,2] // 1,2 are the ids of the Item model } Item model Item { id: 1 ...

JavaScript's equivalent function to jQuery

$.ajax({ url: 'http://' + window.location.host + '/', success: function(data){ $(data).find("a:contains(.jpg)").each(function(){ // will loop through var images = $(this).attr("href"); $('<p></p>').ht ...

Troublesome Bootstrap 4 - Struggling to Expand Background Image Within Div

I am currently working on a website that focuses solely on maximizing screen space. The design includes a logo in the upper center of the page, a full-width navbar, and two rows of three full-width images that may be cropped based on resolution. See the sk ...

Using Vuejs to dynamically render raw HTML links as <router-link> elements

Hey there, I'm just getting started with VueJS and I've been doing some interesting experiments. I created a backend service using Python/Flask that provides me with a string of HTML code containing many tags. My goal is to render this HTML insid ...

Show a single jQuery Validation error

I am struggling with displaying an error message at the top if validation fails, without using the errorPlacement option. Instead, I want to showcase the message in a Bootstrap alert box. Below is the HTML code snippet: <form method="POST" action="/ro ...

Adding an asterisk to mark a required field in Angular reactive form inputs is a simple task that can be accomplished with just a

Currently, I am in the process of developing an application that utilizes a reactive dynamic angular form. The fields for this form are retrieved from an API request and generated dynamically. I have encountered the need to include a 'required field& ...