remove object from JSON array by id after delete f

2020-05-05 00:49发布

I have a json array that looks like:

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"}];

(The above example has 3 objects, but in reality it could have many more.)

And I have an ajax action on my page that will delete the row from the db that one of these objects represents. Rather than refresh my page with the entire json which is many rows and a db call, I would like to just permanently remove the object that is represented by itemID from the array in my page using javascript.

1条回答
爷的心禁止访问
2楼-- · 2020-05-05 01:46

There are many ways of doing it.

The ones that come to my mind:

  1. filtering out an item:

    ad = ad.filter(item => item.itemId != 'DELETED ID');
    
  2. finding index of an item and removing it

    var deletedItem = ad.find(item => item.itemId == 'DELETED ID');
    ad.splice(ad.indexOf(deletedItem), 1);
    
查看更多
登录 后发表回答