Skip to content
Advertisement

Delete record from an array of objects in javascript

I have an array of objects that I get from an api, I get the data but I want to remove the ones that have a finish status after x time.

First I must show all the records, after a certain time the records with FINISH status must be deleted

I am using vue.

This is the response I get:

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

This is the method that obtains the information:

I use setTimeout to be able to delete the records with FINISH status after a certain time

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 tried going through the array and making a conditional and it works for me, but when I call the method again I get the records with FINISH status again. I need to call the method every time since the data is updated

    mounted () {
    this.getTurns();

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

maybe I need to order in another way, or that another javascript method I can use

Advertisement

Answer

Code that you need on CodeSandBox. It sure works.

https://codesandbox.io/s/vue-getdata-and-filter-it-after-delay-6yrj16?file=/src/components/HelloWorld.vue

Use filter for your case: turn => turn.status !== 'FINISH'

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement