I have a JSON object (although for this example I am going to hard-code it into the example) and I would like to delete an item based on its key item
.
I do not want to use the delete [index]
method.
How could I filter my list to get the key-value pair I would like to remove, and then delete that entry only.
I have tried the below but it doesn’t work.
(I am using Javascript)
Thanks
name_array = [ {"item": 1, "name": "John"}, {"item": 2, "name": "Barry"}, {"item": 3, "name": "Sally"} ] filtered_array = name_array.filter((i) => i.item == 2) delete filtered_array[0] console.log(name_array)
Advertisement
Answer
Array#filter is immutable so you should console filtered_array
value its working. No need to use delete
. And change the condition ==
to !==
name_array = [{ "item": 1, "name": "John" }, { "item": 2, "name": "Barry" }, { "item": 3, "name": "Sally" } ] filtered_array = name_array.filter((i) => i.item !== 2) console.log(filtered_array)