Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an object to delete it from objects array javascript?

I have an array of objects and I want to check whether a given object is present in the array and if yes,I want to delete that,If not I have to add it to the array.

I am doing this:

 var arr=[
       {
        name: "Jack",
        type: "Jill",
        },
        {
        name: "Heer",
        type: "Ranjha",
        },
       {
        name: "laila",
        type: "Majnu",
        };

]
 
var tosearch = {
        name: "Jack",
        type: "Jill",
        };
if(arr.includes(tosearch))
{
//I want to delete it from the arr.
}
else
   arr.push(tosearch)

How can I achieve the above implementation?

Thanks

like image 826
rudeTool Avatar asked Dec 05 '25 04:12

rudeTool


2 Answers

You can use this code

arr = arr.filter(item => item !== tosearch)

but, there is better way for handle this you can add an id field for each object and wherever you want to check and find specific item you can use that id

arr = arr.filter(item => item.id !== tosearch.id)
like image 81
Erfan HosseinPoor Avatar answered Dec 07 '25 19:12

Erfan HosseinPoor


Deleting an element from an array using filter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const newArray = existingArray.filter(element => element.id != deleteId);

Searching I usually use a simple findIndex. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

const doesElementExist = arr.findIndex(element => element.id === selectedId);

if (doesElementExist > 0) { // Delete element }

This relies on you having a unique identifier in the object potentially the name? I am not sure what your data will be.

like image 23
Vuk Avatar answered Dec 07 '25 19:12

Vuk