I'm using the following code to update any given property inside a JS object:
var main = {
items: [
{
"name": "T-Shirt",
"description": "Green XL",
"quantity": "1",
},
{
"name": "Shoes",
"description": "Running, Size 10.5",
"quantity": "2",
}
]
};
let project = main.items.find((p) => {
return p.name === 'Shoes';
});
project.quantity = '3';
console.log(main); //shoes quantity is now 3
And it works, however, i want it to also be able to delete the whole project variable (for example, the whole Shoes block). I tried:
let project = main.items.find((p) => {
return p.name === 'Shoes';
});
delete project;
console.log(main); //shoes still exist
But it doesn't work. What would be the best way to delete the property?
Edit: My main issue here was about finding the index of the element to be deleted. The chosen answer below provides the solution.
You can use Array#filter.
main.items = main.items.filter(p => p.name !== 'Shoes');
You cannot use the delete operator like this. To remove the found item from the array in-place, you will want to use Array#splice()
const foundIndex = main.items.findIndex((p) => {
return p.name === 'Shoes';
});
if (foundIndex !== -1) main.items.splice(foundIndex, 1)