请考虑以下数据:
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 } ];
我想从orders数组匹配中删除单个项目food_id
.这是我试过的:
removeFoodOrder(food: Food): void { for (let order of this.orders) { let match = this.orders.filter((order) => order.food_id == food.id); match ? this.orders.splice(this.orders.indexOf(order), 1) : null; break; } console.log(this.orders); }
如果我调用removeFoodOrder(food)
它,它会从数组中删除第一个元素,无论我在params中传递了什么食物.
removeFoodOrder(food) // removes {food_id: 2, table_id: 5} (the first element) // I want to remove {food_id: 1, table_id: 5},
我想从数组中定位匹配元素并删除它的单个实例.我哪里做错了?
你可以使用方法:Array#filter
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(order => order.food_id !== food.id); }
编辑:
由于您的数组允许重复元素,并且您只想删除第一个匹配项,因此您可以使用以下方法:Array#findIndex
const index = orders.findIndex(order => order.food_id === food.id); orders.splice(index, 1);