2017-02-28 73 views
0

後刪除我有一個JSON數組,看起來像:刪除對象的ID從DB

var ad =[{"itemID":"195","issue":"first","buttonText":"First","date":1481200571","link":"https://example.com/link"},{"itemID":"197","issue":"other","buttonText":"Something Else","date":1481200571","link":"https://example.com/linkother"},{"itemID":"215","issue":"main","buttonText":"Important","date":1481200571","link":"https://example.com/linkmain"}]; 

(上面的例子有3個對象,但在現實中,它可以有更多的)

而且我的頁面上有一個ajax動作,它將從數據庫中刪除這些對象所代表的行。我不想用整個json來刷新我的頁面,而是用很多行和一個db調用,我想用javascript來從頁面中的數組中永久刪除itemID所代表的對象。

回答

0

有很多方法可以做到這一點。

浮現在我腦海中的:

  1. 篩選出的項目:一個項目的

    ad = ad.filter(item => item.itemId != 'DELETED ID'); 
    
  2. 發現指數,將其取出

    var deletedItem = ad.find(item => item.itemId == 'DELETED ID'); 
    ad.splice(ad.indexOf(deletedItem), 1); 
    
+0

將選項2永久刪除它?我問,因爲我在頁面上有其他js過濾數組用於其他目的,我想確保該項目將不再被發現... – Stephen

+2

第二個選項將通過引用修改'ad'「。如果您的應用程序的其他部分使用相同的引用,則表示它們將使用更新的版本。 – radmen

+2

使用'findIndex'而不是'find'和'indexOf' – Venugopal