0

New question, so this is the array

[
    0: {
        "id" : "3"
        "name": "David",
        "age": "20"
    },
    1: {
        "id" : "6"
        "name": "",
        "age": "18"
    },
    2: {
        "id" : "8"
        "name": "Micheal",
        "age": "25"
    },
    3: {
        "id" : "9"
        "name": "Wonder Women",
        "age": "20"
    },
    4: {
        "id" : "12"
        "name": "Clark",
        "age": ""
    }
]

How to delete based on id when I click a button? In my app have a delete button to delete this array. I think it need to get array key in order to delete the array.

For example: I can get the id=8, but how can i get array key 2 to delete number 2 array?

If you don't understand, please welcome to comment. Thanks.

Alan Yong
  • 993
  • 2
  • 12
  • 25

4 Answers4

3
array.filter((obj) => {
    if (obj.id != yourId){
        return obj;
    }
})

and don't forget all commas in your objects in array. (after id)

Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
1

Suppose your array is like:

 arr = [
  {"id":"3","name":"Clark"},
  {"id":"6","name":"David"},
  {"id":"8","name":"Miche"}
];

id = 6;

arr = $.grep(arr, function(data, index) {
   return data.id != id
});

Now finally this will return array with removing record of id=6

Pradip
  • 476
  • 3
  • 3
1

if you want to directly manipulate the contents of an array instead of returning new array, you can try this

let index = array.findIndex(obj => obj.id == objIdToDelete)
if(index != -1) { array.splice(index, 1) }

check Array.prototype.splice() to know more

tony.hokan
  • 541
  • 5
  • 7
0

Suppose your array was stored in obj, you can use lodash function remove to remove an item in an array in the following way.

_.remove(obj, function(currentObject) {
    return currentObject.id == "8";
});

Which will remove the item '2' containing '8' from your array

hendrixchord
  • 4,662
  • 4
  • 25
  • 39