How do I remove an object from an array with a matching property?
The first step for me is always to remove anything confusing like that ternary operator and your break stmt. Here's how I did it
let food = {
id: 1,
name: 'Pizza',
price: 16
}
let orders = [
{food_id: 2, table_id: 5},
{food_id: 2, table_id: 5},
{food_id: 1, table_id: 5},
{food_id: 3, table_id: 5},
{food_id: 1, table_id: 5}
]
for (let order of this.orders) {
if (food.id === order.food_id) {
this.orders.splice(this.orders.indexOf(order), 1);
break;
}
}
console.log(this.orders);
I would recommend against using Array#filter if you don't know 100% how to use it.
UPDATE I am not saying don't use the Array#filter method. I'm just saying that if your code isn't working, you should try to remove anything that could be causing your issue and try to go about it step by step using simple constructs (like a for loop and if stmt).
You could use Array#filter
method:
food = {
id: 1,
name: 'Pizza',
price: 16
};
orders = [
{ food_id: 2, table_id: 5 },
{ food_id: 2, table_id: 5 },
{ food_id: 1, table_id: 5 },
{ food_id: 3, table_id: 5 },
{ food_id: 1, table_id: 5 }
];
removeFoodOrder(food: Food): void {
this.orders = this.orders.filter(({ food_id }) => food_id !== food.id);
}
Edit:
Since your array allows duplicate elements and you want to remove only the first match, you could use the Array#findIndex
+ Array#filter
methods:
const foundIndex = this.orders.findIndex(({ food_id }) => food_id === food.id);
this.orders = this.orders.filter((_, index) => index !== foundIndex);