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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With