簡體   English   中英

從 javascript 中的對象數組中刪除記錄

[英]Delete record from an array of objects in javascript

我有一個從 api 獲得的對象數組,我得到了數據,但我想刪除那些在 x 時間后具有完成狀態的對象。

首先我必須顯示所有記錄,一定時間后必須刪除具有 FINISH 狀態的記錄

我正在使用 vue。

這是我得到的回應:

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

這是獲取信息的方法:

我使用 setTimeout 能夠在一定時間后刪除具有 FINISH 狀態的記錄

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));
}

我已經嘗試遍歷數組並設置條件,它對我有用,但是當我再次調用該方法時,我再次獲得具有 FINISH 狀態的記錄。 由於數據更新,我每次都需要調用該方法

    mounted () {
    this.getTurns();

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

也許我需要以另一種方式訂購,或者我可以使用另一種 javascript 方法

filter正是您所需要的。 我不明白為什么您將所有內容都包裝在setInterval中並等待 5 或 6 秒。

為什么不返回過濾后的數據呢?

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

你在這個地方弄錯了this.turns = data;

它將data放在過濾turns之前的組件屬性中;

過濾后做:

 .then(data => { // get before filter this.turns = data; // filter data after 6 sec setTimeout(() => { data.forEach(turn => { this.turns = data.filter(turn => turn.status;== 'FINISH'); }), }, 6000) })

抱歉,但我不明白您為什么在fetch中使用setTimeout 你確定有必要嗎?

如果您按原樣使用 promise,則可以避免setTimeout()延遲:一個 promise,一些數據將在那里!

以下代碼段將在從遠程數據源(在此示例中只是一個沙箱服務器)接收到數據后立即提供全局變量turns中的數據。 然后過濾數據以排除屬性.company.catchphrase包含單詞“零”並放入全局變量turns中的任何條目。 function getTurns() (返回 promise。 .then()之后的 .then() 中的回調只會在 promise 被解析后觸發。

 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);

CodeSandBox 上您需要的代碼。 它確實有效。

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

為您的情況使用過濾器: turn => turn.status !== 'FINISH'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM