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

Having difficulty sending emails with attachments using AngularJS

While using Angular, I encountered an issue when sending an email with an attachment. The response I received contained the data code of the file instead of its actual format. See example: https://i.stack.imgur.com/vk7X8.png I am unsure what is causing t ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Create a random number on the server every X interval

Context I have developed a Node.js application that generates a random number every 6 seconds and exposes it through an API. To maintain separation of concerns, I decided to encapsulate the number generation logic in a function called numberGen, stored i ...

Whenever I try to execute the command `electron .` in the electron-quickstart project, I immediately encounter an error within the

Upon successfully installing Electron, I attempted to run it using "electron" or "electron -v" commands. Unfortunately, I encountered an error while running it on Windows 10. C:\Windows\System32\electron-quick-start>electron -v modu ...

What is the method for opening the command prompt while initializing a node.js server?

I've successfully set up a node.js server and now I'm looking to send a command to the prompt upon startup. This is something I couldn't manage while the server was already running. Should I be implementing this from within the server.js fi ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

Is it feasible to insert the result of a JavaScript code into a PHP script?

Alternatively, you can view both codes side by side on the panelbackup(dot)com/codes page Alright, I have a code placed on page 1.html that adds four random numbers at the end of any given URL: <head><script>window.onload = function() { ...

How can I verify if an SVG file has a reliable source? (having troubles converting SVG to canvas)

While attempting to use an SVG generated by a chart plugin (https://wordpress.org/plugins/visualizer/), I am facing issues retrieving the source of the SVG-image being created. Interestingly, when using other SVGs with the same code, everything works perfe ...

Utilizing Asynchronous Functions within a Loop

I have a situation where I am working with an array and need to make API calls for each index of the array. Once the API call is resolved, I need to append the result in that specific element. My goal is to ultimately return the updated array once this pro ...

Utilize Vue's map state feature to efficiently bind an array to a v

I've been focusing on developing custom fields within my application. Users now have the ability to create custom fields for different objects (e.g., Initiative) and view them when updating or adding that object. Within my state, I specify the object ...

Retrieve a value from a PHP database table and transfer it to a different PHP webpage

I have values retrieved from a database and I need to select a row from a table and pass those values to the next PHP page, OInfo.php. I attempted to use Javascript to place those values in textboxes, but upon clicking the continue button, the values are n ...

What are the steps involved in incorporating a REST API on the client side?

Hey there! Today I'm working with a simple Node.js express code that functions as a REST API. It works perfectly when I use Postman to send requests with the GET method, as shown in the code below. However, when I try to implement it on the client sid ...

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Troubleshooting Issues with https.request and Options in NodeJS Leading to Connection Resets

When working with NodeJS, I noticed that my code performs as expected when using https.get() to retrieve responses. However, the moment I make the switch to https.request() along with requestOptions, I encounter a connection reset error along with the foll ...

What is the best way to implement collision detection using raycasting?

For my university project, I am looking to implement collision similar to what is shown in this example. However, I am facing an issue where collision is only working on the top of the object. I referred to this for guidance. My goal is to add collision to ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

The event listener activates multiple times on HTML pages that are dynamically loaded with AJAX

Javascript utility function: // This event listener is set using the on method to account for dynamic HTML $(document).on('click', '#next_campaign', function() { console.log('hello'); }); Website layout: <script src=&q ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...