remove item from list of objects

Currently, I am actively using vuejs 3 in conjunction with laravel.

This is the object array that I am currently working with:

[[Target]]
: Array(3)
0: Proxy(Object) {id: '96', name: 'DESINCRUSTADOR DCALUXE - HIDROCAL ELECTRONICO', category: 'ARTICULOS B'}
1: Proxy(Object) {id: '56', name: 'ECONOMIZADOR DE AGUA ROSCA HEMBRA', category: 'ARTICULOS SECUNDARIOS'}
2: Proxy(Object) {id: '291', name: 'COLECCIÓN COCINA INTERNACIONAL, ALTA GASTRONOMÍA I…UILIBRADA Y SALUDABLE. HD - 3D, 2 TOMOS+1DVD (GD)', category: 'OBRAS LITERARIAS PEQUEÑAS'}
length: 3

In addition, I have a function designed to remove elements from my table:

const removeItem = (event) => {
        event.target.parentElement.parentElement.remove()

The deletion of the row works as intended, but now I need to update the content of my array, which is set as a ref([]).

const addItemCart = ref([])

To accomplish this task, I am experimenting with the following code snippet:

let allRow = event.target.parentElement.parentElement;
        let firstTd = allRow.getElementsByTagName('td')[0].textContent

        addItemCart.value.forEach(element => {
            if(element.id == firstTd){
                for (const property in addItemCart.value) {
                    addItemCart.value = addItemCart.value.filter(item => addItemCart.value.id != firstTd);
                }
            }
        });

        console.log(addItemCart.value)

Initially, I fetch the tr element followed by extracting the content of the first td, which stores the ID. Subsequently, I attempt to locate any matches within the array based on the id value and aim to eliminate them. This action is necessary as whenever I add new items using the push function, the previously selected items persist alongside the new ones.

What approach should I take to successfully remove these items from my array?

Update:

const removeItem = (event) => {
        event.target.parentElement.parentElement.remove()

        let allRow = event.target.parentElement.parentElement;
        let firstTd = allRow.getElementsByTagName('td')[0].textContent

        addItemCart.value.forEach(element => {
            if(element.id == firstTd){
                if(element.id == firstTd){
                    for (const property in addItemCart.value) {
                        if(property.includes(firstTd)){
                            console.log("está");
                        }else{
                            console.log("no rula")
                        }
                        //addItemCart.value = addItemCart.value.filter(item => addItemCart.value.id != firstTd);
                    }
                }
            }
        });

        console.log(addItemCart.value)

I appreciate your assistance and apologize for any language barriers.

Answer №1

After much consideration, I have come up with a simple solution to my problem:

First, I identify the click location in my table and retrieve its parent element. Then, I extract the index from my array that is assigned to the td element's id.

I made adjustments to my v-for loop like this:

<tr v-for="(item, index) in addItemCart" :key="item.id">
                                    <td :id="index">{{ item.id }}</td>
                                    <td>{{ item.name }}</td>
                                    <td>{{ item.category }}</td>
                                    <td><i class="fa fa-trash" aria-hidden="true" @click="removeItem($event)"></i></td>
                                </tr>

In my removeItem() function:

const removeItem = (event) => {
        event.target.parentElement.parentElement.remove()

        let allRow = event.target.parentElement.parentElement;
        let firstTd = allRow.getElementsByTagName('td')[0].id;

        var index = addItemCart.value.indexOf(firstTd);
        addItemCart.value.splice(index, 1);
    }

As a result, I am now able to delete both the row and the corresponding item from the array.

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 functionality of scrolling ceases to work once the bootstrap modal is closed

I am utilizing Bootstrap v3.1.1 to showcase a modal popup on one of my web pages. The following code shows how I have implemented it. <!--Start show add student popup here --> <div class="modal fade" id="add-student" tabindex="-1" role="dialog" a ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

What is the best way to transmit extra data when tunneling a TLS connection?

I have developed a basic HTTP proxy that utilizes the HTTP CONNECT method for HTTP tunneling. const http = require('http'); const https = require('https'); const pem = require('pem'); const net = require('net'); con ...

What is preventing me from being able to access a property within my function?

In the post method below, I am trying to access baseUrl. However, it is showing undefined. Can you help me understand why and provide a solution? const API = { baseUrl: "http://my_api_address", post: (path, payload) => { let headers = { ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

Ways to track all requests completed in Nuxt 3

I am looking to create a unique loading page that conceals itself once all requests and static data have been loaded, including static images and libraries. How can I determine when all requests and static data have finished loading? I have attempted the ...

Guide to inputting text into the Dev element

I am encountering a challenge with automating gist creation on GitHub. The issue arises when trying to input text into the gist content-box (see attached image). Despite attempting to use Javascript executer, I have not been successful. JavascriptExecutor ...

The function passed to the modal is not functioning correctly when stored within the state

Is it possible to create a unique modal that can be utilized for multiple actions on the same page? To achieve this, I have implemented a state to store the title, description, and submit function for modal click and modal open state. In addition, I want t ...

Cannot get v-if to work with multiple conditions

<template> <div> <h2>{{weatherData.city}}</h2> <h3>{{weatherData.weather}}</h3> <rain-cloud v-if="iconSelect==='09d'"/> <sun-cloud v-if="iconSelect==='04d'"/> <sunsh ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

Using AngularJS to compare values against user input to determine if they are greater or lesser

When a user inputs data into an input field, it must fall within the range of values retrieved from the database. The value entered by the user should meet either the minimum, maximum, or default value obtained from the database. For instance, if the minim ...

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...