Removing a data entry from an array of objects using javascript

I have retrieved an array of objects from an api, and while I am able to successfully fetch the data, I am looking for a way to automatically remove objects with a "FINISH" status after a certain period of time.

Initially, all records should be displayed, but those with a "FINISH" status need to be removed after a specified time duration.

I am currently utilizing Vue.js for this task.

This is the response I receive:

[
      {
        "id": "289976",
        "status": "FINISH"
      },
      {
        "id": "302635",
        "status": "PROGRESS"
      },
      {
        "id": "33232",
        "status": "PROGRESS"
      }
    ]
    

This is the method responsible for fetching the information:

I am using setTimeout to schedule the deletion of records with a "FINISH" status after a specific time interval

getTurns() {
            fetch('ENPOINT', {
                method: 'POST',
                body: JSON.stringify({id: this.selected}),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => response.json())
              .then(data => {
                                
                this.turns = data;

                data.forEach(turn => {

                    if(turn.status == 'FINISH'){
                        setTimeout(() => {
                            this.turns = data.filter(turn => turn.status !== 'FINISH');
                        }, 6000);
                    }

                });
                
               })
              .catch(error => console.error(error));
    }
    

I have attempted to create a conditional loop through the array which works successfully. However, upon calling the method again, I found that records with a "FINISH" status reappear. Since the data continuously updates, I need to call the method frequently.

mounted () {
        this.getTurns();

        setInterval(() => {
            this.getTurns();
        }, 5000);
       }    
    

Perhaps there is another approach or JavaScript method that could address this issue more effectively.

Answer №1

filter does the trick. No need to complicate things by using setInterval and waiting for several seconds.

Just return the filtered data directly.

return data.filter(item => item.status !== 'FINISHED');

Answer №2

Your error lies in this specific location this.turns = data;

The code places data into the component property turns before filtering it;

Instead, perform the action after filtering:

.then(data => {
  // Retrieve data before applying filter
  this.turns = data;
  
  // Apply filter to data after 6 seconds
  setTimeout(() => {
    data.forEach(turn => {
      this.turns = data.filter(turn => turn.status !== 'FINISH');
    });
  }, 6000)
})

I'm a bit perplexed as to why you are utilizing the setTimeout function inside the fetch method. Are you certain that it is necessary?

Answer №4

To avoid the delay caused by setTimeout(), it's important to understand that a promise guarantees the availability of data in the future.

This code snippet demonstrates how data is fetched from a remote source (such as a sandbox server) and stored in the global variable turns. Entries with the word "zero" in the property .company.catchphrase are filtered out before being assigned to turns. The callback function within the .then() method executes only after the promise returned by getTurns() has been fulfilled.

var turns; // global variable 
function getTurns() {
  return fetch("https://jsonplaceholder.typicode.com/users")
          .then(r => r.json()).then(data =>
             turns=data.filter(turn=>!turn.company.catchPhrase.includes("zero"))
          )
          .catch(error => console.error(error));
}
getTurns().then(console.log);

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

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

The Kendo Grid is refusing to show up within the popup window

I am new to using Angular 2 and Kendo UI. Currently, I am attempting to include a grid inside my pop-up window. While I have successfully displayed the pop-up, adding the grid has proven challenging. The grid is not appearing as expected ...

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

Is there a way to customize the look of the time selected in the <input matInput type="time" step="1" /> time picker?

Currently, I am utilizing the following code as a time picker in my Angular 9 application. My goal is to modify the selected time's color to a bright blue shade. How can I accomplish this task? <input matInput type="time" step="1&quo ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Using jQuery AJAX to send POST requests in CodeIgniter

I've been trying to configure the jQuery Ajax post URL, but it's not functioning as expected. I've searched extensively and found many solutions, but none of them seem to solve my issue. I've set the base URL in var baseurl = "<?php ...

Save the list of arrays into a designated variable

I am struggling to save the array list in a variable and I'm not sure how to go about solving this issue. The xpath query successfully retrieves a list of items, which are being displayed in the console without any problems. However, I am unable to f ...

Turn off the autofill option for passwords in Google Chrome

Is there a way to prevent the password autocomplete dropdown from appearing when clicking on the password field? In Chrome Version 61.0.3163.100, none of the solutions seem to be working. Screenshot This issue has been raised many times, but setting autoc ...

Loading textures in ThreeJS can cause a momentary display of black when using Firefox

I am currently working on implementing an undo/redo feature for a 3D paint tool. The process involves storing the texture in an array after each draw using the following code: var image3 = mesh.material.map.image; var testCanvas = image3.g ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

I am struggling with utilizing the data that has been fetched in JavaScript. Despite successfully retrieving the data, I am facing difficulties in effectively using it in

I am facing an issue where I am unable to utilize the data after fetching it from a local JSON file. Below are the screenshots showcasing the problem: Here is the data displayed in the console: Here is the code snippet: fetch('api_link.json') ...

Using React.js and mdbottstrap to display a Modal when clicking

I'm struggling to get a modal to open with a click on my page. The button is there, but clicking it doesn't trigger the modal to appear. I've been searching for a solution without any luck so far. function ModalPage(props) { const [usern ...

The Laravel API successfully retrieves data in Postman, but when trying to access it in Vue.js, only an

I've been working on a small Laravel API that should respond when an endpoint is accessed. The issue I'm facing is that while the same endpoint returns data in Postman, it appears empty in Vue Js. I've been trying to figure this out for the ...

Unable to successfully modify data in CRUD operations through AJAX and JQuery

I'm currently practicing CRUD operations with AJAX and JQuery. I have successfully implemented adding and retrieving data from the database using ADO, but I am facing challenges with updating the data in the CRUD operations. I need some assistance! H ...

Having trouble parsing the body parameter in Express for a POST request

I am encountering difficulty in accessing the body parameters of a request using Express: const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const app = express(); con ...

Utilizing the focus or click functionalities in Internet Explorer when working with a datepicker

Encountering an issue with the datepicker in IE8+. The code functions properly in all other browsers tested, but unfortunately our client is limited to using IE8. The problem occurs when clicking on the field to bring up the datepicker. Attempting to sele ...

Is it possible to exchange a JavaScript array with JSON content in a Search Application?

Greetings to all you fantastic individuals! I have developed an application where the script search.js searches through a JavaScript array to display a list of results when a user types in a keyword into a search bar and hits enter. However, I am now facin ...

Converting an array value into JSON structure

I'm currently working on an email application that allows users to send messages. Everything is functioning well except for the recipients column. I temporarily hardcoded an email address to test the functionality, but in reality, the recipients field ...