Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit {

  title = 'bucketList';
  bucketList: BucketListItem[] = [
    new BucketListItem(
      "Goa Trip",
      "Travel to Goa"
    )
  ];

  ngOnInit() {

  }
  onItemAdded(eventData) {
    this.bucketList.push(new BucketListItem(eventData.itemName, eventData.itemDescr));
  }
  onItemDeleted(delData) {   //delData = "Goa Trip"
    console.log(this.bucketList); //prints {"itemName":"Goa Trip","itemDescr":"Travel to Goa"
    this.bucketList = this.bucketList.filter(function (obj) {
      return obj.itemName !== delData;
    });
    console.log(this.bucketList);  //prints {"itemName":"Goa Trip","itemDescr":"Travel to Goa"
  }
}

The goal is to eliminate an element from the array by matching its itemName, specifically when itemName equals "Goa Trip". However, the removal process does not succeed.

Answer №1

To ensure proper filtering, make sure to assign the value after applying the filter.

myBucketList = myBucketList.filter(function (item) {
      return item.name !== 'Goa Trip';
});
console.log(myBucketList);

Answer №2

The problem lies in the setup of your BucketListItem object. Below is a simple example that demonstrates the issue:

class App {

    title = 'bucketList';
    bucketList = [
        {
            itemName: "Goa Trip",
            itemDescr: "Travel to Goa"
        }
    ];
    add(data) {
        this.bucketList.push([data.itemName, data.itemDescr]);
    }
    delete(delData) {   //delData = "Goa Trip"
        console.log(this.bucketList); //prints {"itemName":"Goa Trip","itemDescr":"Travel to Goa"
        this.bucketList = this.bucketList.filter(function (obj) {
            return obj.itemName !== delData;
        });
        console.log(this.bucketList);  //prints {"itemName":"Goa Trip","itemDescr":"Travel to Goa"
    }
}

After setting up the above code, you can execute the following commands:

const app = new App()
app.delete('Goa Trip')

It should work as intended. In your case, "itemName" is enclosed in double quotes, indicating that either the quotes are part of the property's literal name or it's JSON rather than a JavaScript object.

To resolve this, try the following:

this.bucketList = this.bucketList.filter(function (obj) {
    return obj['"itemName"'] !== delData;
});

If this change works, then the issue is due to the presence of double quotes in the item's literal name. If there is no property named itemName but instead "itemName", your filter method won't match anything.

Answer №3

After some investigation, I identified the issue as being caused by extra spaces before and after the itemName. To rectify this, I implemented the javascript trim() function and now the problem has been resolved successfully.

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

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

AngularJS presents an error: [ng:areq] The argument 'myAppCtrl' is not recognized as a function, as it returns undefined while implementing routes with ngRoute and $routeProvider

Can anyone assist me with an error I'm encountering while setting routes on two buttons? Despite having everything properly defined, the table is not displaying any data. Your insights would be greatly appreciated. Thank you for your help. Snippet f ...

Implementing Server-Side API Response Caching in React-Query and Next JS

My server-side rendering setup with react-query is working smoothly. I am aware that react-query stores a cache on the client side to serve data if the query key is fresh and available. Here is the code snippet depicting this setup - // pages/_app.tsx imp ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

An Angular ng-container situated within a row of an HTML table

I am currently working with a Reactive Form that includes a FormArray (similar to a Game Roster containing basic information such as Start At, Prize, Duration, and an array of players). To display the array of players, I have implemented the following: & ...

When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet: 'use strict' import React from 'react' import { connect } from 'react-redux' import { Panel, Col, Row, Well, Button } from 'react-bootstrap' const Cart = ({ cart }) => { const cartI ...

Establish a connection using node.js to enable communication between a server and a client

Running a node.js Server:- // *********** Setting up a server to receive orders ************ // // requiring the http module. // var http = require('http'); // initializing request variable as an empty string. // var req = ""; // creating th ...

Is condition checking taken into consideration by Typescript?

I keep encountering this strange TypeScript compile warning that just won't go away, even though I believe it shouldn't be there in the first place... Here are the interfaces I'm working with: interface Props { tasks: TaskType[] } inter ...

Utilizing Typescript to Incorporate Bable's Latest Feature: The 'Pipeline Operator'

Exploring the pipeline operator implementation in my Typescript project has been quite a journey. Leveraging babel as my trusty transpiler and Typescript as the vigilant type checker was the initial plan. The quest began with configuring babel to work sea ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

Retrieving data from the database using getStaticProps in Next.js

As I was following a tutorial on Next.js, the instructor did something that deviated from what I had learned in school and left me pondering. Here is what he did: interface FaqProps { faq: FaqModel[]; } export default function Faq({ faq }: FaqProps) { ...

Avoiding duplication of prints in EJS template files

In my EJS code, I have created a loop to fetch the total amount of items from the database. Here is my current code: <h2>Summary</h2> <% if(typeof items.cart!=="undefined"){ var amount = 0; %> <% i ...

Switching perspective in express with Pug

Hello everyone, I'm still getting the hang of using Node.js with Express and Jade. I've successfully set up a basic 1 page app where a login page is displayed by default. Once the user logs in and is authenticated against a database, the function ...

Attempting to enhance the modularity and readability of my code

Looking for assistance to enhance the modularity and readability of this lengthy code. Any tips on how to simplify it and improve clarity would be greatly appreciated! I'm currently working on a street fighter game, and here's what I have so far ...

JavaScript validation code for verifying hostnames with a specified domain name

I need a customized validation check for my order form where users are asked to enter their server hostname. The challenge is that I'm using WHMCS with encrypted PHP code and IonCube loaders, making it difficult to add this check. Users can input any ...

Utilize Node.js to proxy Angular requests to a service hosted on Azurewebsites

I am trying to set up a proxy post request in my Node.js server and receive a response from the target of this request. Below is an excerpt from my server.js file code where I have implemented the proxy, but I am facing a issue with not receiving any respo ...

"Receive your share of the catch in a pop-up notification

Is there a way to determine if a user shared a result without using the social network's Javascript SDK? All sharing aspects (authorization, sharing, etc.) are done through popups on my domain. var popup = window.open('/api/share/' + servic ...

Determine the quantity within the data array using javascript

My dataset contains an array with thousands of objects structured like this: var data = [ {type:'A',time:'2009'}, {type:'A',time:'2009'}, {type:'A',time:'2009'}, {type:'A',time: ...